mvc 3 nested objects binding
I am very new to MVC 3 so this could be an easy one. I have a viewmodel with a nested object like this:
public class EventViewModel
{
public Event Event { get; set; }
}
public class Event
{
[Required]
public int Id { get; set; }
public string Title { get; set; }
}
In my 'create' view I do something like this:
@model EventViewModel
@Html.EditorFor(model => model.Event.Title)
Here's the code form my event controller:
public class EventController : Controller
{
[HttpPost]
public ActionResult Create(EventViewModel @event)
{
...
}
}
开发者_如何学JAVA
This editor is inside of form tag. When i postback to my controller the title of the event is null instead of what i entered in the form. Do I need some kind of custom binder? Am I doing something unconventional when I use nested objects in my viewmodel?
It's the name of your parameter. Change it from @event to eventViewModel. Seems like the model binder cannot bind it like that. Possibly it gets mixed up with the Event property on your model.
public ActionResult Create(EventViewModel eventViewModel) {..}
Edit: Some more rough explanation.
The HtmlHelper creates a form input with the name Event.Title and when you are doing the binding on the post, the binder will first try to bind Event.Title to the parameter named event, to the property called Title. Since there is no such property on the EventViewModel this will be null. You can see test this by changing the parameter type from EventViewModel to Event (which has a property called Title), in which case the binding will not be null.
Instead if the parameter is named something else, it will try to bind it to that parameter by looking first for a property called Event, and then Title instead.
Changing the name of my nested class to TheEvent fixed the problem somehow...this is what my viewmodel looks like now..
public class EventViewModel
{
public Event TheEvent { get; set; }
}
Oh right. When you request the page for the first time, i.e. your default action, you need to instantiate the ViewModel and pass that to the view.
public ActionResult DefaultActionForEventView()
{
var eventViewModel = new EventViewModel();
eventViewModel.Event = new Event() // I can't remember if you need this line
return View(eventViewModel)
}
Let me know about the line above.
精彩评论