MVC 3 split options in HttpPost action
I have an MVC 3 application and I created a generic wrapper object that has some navigation properties and a wrapped T object whose values I edit / display.
public class NavigationViewModel<T>
{
public T Model { get; set; }
public NavigationHelper NavigationHelper { get; set; }
public NavigationViewModel() { }
public NavigationViewModel(T model, NavigationHelper helper)
{
this.Model = model;
this.NavigationHelper = helper;
}
}
My controller resolves this object perfectly in the following activity:
public ActionResult Foo(NavigationViewModel<Bar> viewModel)
The code in my view looks like this:
@Html.EditorFor(model => model.Model.SomeProperty)
A colleague of mine said this code is a good read. I already have a strongly typed view, Model and this model has another property called Model. He proposed to rename the Model property to ViewModel, and I agreed with his reasoning.
Now the code with renamed properties no longer works: NavigationViewModel viewModel is null. So I replaced the HttpPost method signature with the following and it works again:
[HttpPost]
public ActionResult Foo(NavigationHelper helper, Bar viewModel)
I love it! I can directly access my viewModel in code, the code in the view makes sense and the helper does not get in the way. I have not seen this convention before and I am assuming it worked before due to the naming convention. Using a property called Model hints at how to resolve the object. Without this property, he could no longer resolve it.
I would like to accept this for other types of helpers that contain view-specific properties such as select lists or other properties that I could put into my ViewBag. Could you guys recommend this approach or I might run into a problem later using this?
source to share
I think I have a very simple answer for you, just don't call your parameter actionModel, so change:
public ActionResult Foo(NavigationViewModel viewModel)
public ActionResult Foo(NavigationViewModel model)
Or any other parameter name that doesn't clash with your ViewModel property in your NavigationViewModel class.
source to share