Hi guys,
Is there any analog to Django forms (http://docs.djangoproject.com/en/dev/topics/forms/?from=olddocs) in ASP.NET MVC 2?
Hi guys,
Is there any analog to Django forms (http://docs.djangoproject.com/en/dev/topics/forms/?from=olddocs) in ASP.NET MVC 2?
I have listed out the "main topics" listed on the link you supplied...
1 - Display an HTML form with automatically generated form widgets.
In ASP.NET MVC you can use Html.EditorFor(Model) to auto-generate an entire form. You can add attributes to the model for any data items that you don't want to scaffold.
This will generate an entire form with fields for each property.
<%= Html.EditorFor(m => m) %>
Or you can use it on individual properties
<%= Html.EditorFor(m => m.FirstName) %>
or you can tell it what element you want
<%= Html.TextBoxFor(m => m.FirstName) %>
2 - Check submitted data against a set of validation rules.
There are lots of ways to validate the data in ASP.NET MVC. You can add attributes to make items on the model mandatory, or to ensure their value is within a range, etc. In MVC 3, you will also be able to implement an "IValidatable" interface, which will add a "Validate()" method to your object that you can add your own custom rules to.
3 - Redisplay a form in the case of validation errors.
This is MVC out of the box, you should post back to the same page. It will automatically add CSS classes to the items that fail validation and will populate and validation place holders / validation summary.
<%= Html.TextBoxFor(m => m.FirstName) %>
<%= Html.ValidationMessageFor(m => m.Firstname) %>
4 - Convert submitted form data to the relevant Python data types.
Again, this is out-of-the-box stuff. If you post a form to an action, MVC will get the data into your model.
[HttpPost]
public ActionResult Edit(CustomerModel model) {
// model will automatically populated from the form post...
// Any validation attributes you placed on the model and
// any "natural" validation issues will already have been
// checked (i.e. someone typing "A" into a field that is an int
// on your model
if (ModelState.IsValid) {
_myRepository.Save(model);
return RedirectToAction("Detail", new { id = model.Id });
}
// If validation has failed, you can just return the view again
// so the user can correct the errors
return View(model);
}