Monday, May 16, 2011

MVC validation on controller.

The following link has very useful information for validation of mvc .

Before in my knowledge, I do understand the validation of mvc has to be placed on the model layer. That gives some headache to me to find right entity in entities.

That a pieces of codes saves my headache. That's just brilliant. Thanks to who posted this post.

public ActionResult Add()
return View();

public ActionResult Add(FormCollection form)
var movieToAdd = new Movie();

// Deserialize (Include white list!)
TryUpdateModel(movieToAdd, new string[] { "Title", "Director" }, form.ToValueProvider());

// Validate
if (String.IsNullOrEmpty(movieToAdd.Title))
ModelState.AddModelError("Title", "Title is required!");
if (String.IsNullOrEmpty(movieToAdd.Director))
ModelState.AddModelError("Director", "Director is required!");

// If valid, save movie to database
if (ModelState.IsValid)
return RedirectToAction("Index");

// Otherwise, reshow form
return View(movieToAdd);

No comments: