Weird data binding behavior in ASP.NET MVC3?
I have the following domain objects:
public class Foo
{
public Id {get; set;}
**public BarId {get; set;}**
public virtual Bar {get; set;}
public string Name {get; set;}
}
public class Bar
{
public Id {get; set;}
public string Name {get; set;}
}
The view model used by the view looks like this:
public class FooEditorModel
{
public Foo {set; get;}
public SelectList Bars { get; set; }
}
The view looks like this:
@model FooEditorModel @Html.ValidationSummary( true ) @Html.HiddenFor( model => model.Foo.Id ) @Html.LabelFor( model => model.Foo.BarId, "Bar" ) @Html.DropDownListFor( model => model.Foo.BarId, Model.Bars ) @Html.ValidationMessageFor( model => model.Foo.BarId )
The controller looks like this:
[HttpPost]
public virtual ActionResult Save( FooEditorModel model )
{
if ( ModelState.IsValid )
{
Foo foo = MakeAModel( model );
FooRepository.Save( foo );
}
}
Foo MakeAModel( model )
{
Foo foo = MakeAFoo();
**foo.BarId = model.Foo.BarId;**
return foo;
}
Quite standard code, a bit simplified.
The problem is that if I use a Bar in Foo, instead of BarId , the ModelState is not valid (because of Bar.Name).
I find it very poorly designed to be forced to have both a child Id and a reference to the child in the root object.
Is this the only way for a data binding to work in MS MVC 3?
链接地址: http://www.djcxy.com/p/60448.html