I'm exper开发者_JAVA百科imenting with the unobtrusive client validation and have been struggling to get it to work in my scenario.
My main problem is that my view has a strongly typed ViewModel. This ViewModel contains several collections that are used to populate dropdowns and has an additional property (let's call it Person) which is the actual object I wish the form to edit.
My controller action handling the post expects to get a Person object not the entire ViewModel posted. So I haven't been able to use:
@Html.TextBoxFor(m => m.Person.Name)
because I need the input control to have a name = "Name" and not "Person.Name" I can correct this by using
@Html.TextBox("Name", m.Person.Name)
But then the resulting input control lacks the data-* attributes client validation needs. Is there a way to get client validation to work, keep my viewmodel, and make my controller action all work together?
On a side note it seems like the data-* attributes on form fields are only added if you use
@using (Html.BeginForm())
Writing out my own <form>
tag by hand seems to break it.
Is using the form helper required?
well in scenario that you outlined, your properties' names will be prefixed with Person like
<input type='text' name='Person.Name'..../>
<input type='text' name='Person.Age'.../>
where Name and Age are properties of Person object respectively. you can write you post action method like
[HttpPost]
public ActionResult Index(Person Person)
{
//handle person here
}
The catch here is that if you receive object with name of Prefix in your form elements modelbinder will be able to populate it. if it does not work (it did work for me) you can use Bind(Prefix="")
attribute when binding you object in post action method. For example usage of bind have a look at How to use Bind Prefix?
You have to decorate the ViewModel attributes that you want validated with a [Required]
annotation like this...
using System.ComponentModel.DataAnnotations;
.....
public class MyViewModel
{
.....
[Required]
public string Name { get; set; }
.....
}
精彩评论