Tuesday, April 23, 2013

ASP.NET MVC Adds NULL Record


Let's say you have a controller method like below which used to submit a record to the database.

public ActionResult Create(person ob)
 { 
 if (ModelState.IsValid) 
 {
 context.Save();// save record to database
 return View(ob); 
 }
 else 
 {
 return View(ob); 
 }
 }

Above method will add a record to the database each time you load the view, that is before you submit the form. This happens because this method is used for both GET and POST requests. To avoid adding a null record modify the code as below.

[HttpPost]
public ActionResult Create(person ob)
 { 
 if (ModelState.IsValid) 
 {
 context.Save();// save record to database
 return View(ob); 
 } else 
 {
 return View(ob); 
 }
 }

[HttpGet] 
public ActionResult Create() 
{ 
 return View(); 
}

Now on the page load you will access the page via GET request and when the form is submitted POST method will fire.

No comments:
Write comments
Recommended Posts × +