Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var myViewModel = new CreateFavoriteListViewModel();
var favoriteTypeDropdownList = new List<SelectListItem>();
favoriteTypeDropdownList.Add(new SelectListItem { Text = "Text1", Value = "1" });
favoriteTypeDropdownList.Add(new SelectListItem { Text = "Text2", Value = "2" });
myViewModel.FavoriteTypeDropdownList = favoriteTypeDropdownList;
return View(myViewModel);
}
[HttpPost]
public ActionResult Post(CreateFavoriteListInputModel createFavoriteListInputModel)
{
return new EmptyResult();
}
}
Models:
public class CreateFavoriteListViewModel
{
public CreateFavoriteListInputModel CreateFavoriteListInputModel { get; set; }
public List<SelectListItem> FavoriteTypeDropdownList { get; set; }
}
public class CreateFavoriteListInputModel
{
[Required]
public string ListName { get; set; }
public int SelectedFavoriteType { get; set; }
}
View:
@model MvcApplication3.Controllers.CreateFavoriteListViewModel
<h2>title</h2>
@using (Html.BeginForm("Post", "Home", FormMethod.Post))
{
@Html.LabelFor(x => x.CreateFavoriteListInputModel.ListName)
@Html.TextBoxFor(x => x.CreateFavoriteListInputModel.ListName)
@Html.LabelFor(x => x.CreateFavoriteListInputModel.SelectedFavoriteType)
@Html.DropDownListFor(x => x.CreateFavoriteListInputModel.SelectedFavoriteType, Model.FavoriteTypeDropdownList)
<input type="submit" value="Save" id="btnCreateList" name="btnCreateList" />
}
As you can see I use an input model with a special lambda expression. (x=>x.CreateFavoriteListInputModel.ListName).
The strange problem is that this does work on my home computer but not on my companies one (createFavoriteListInputModel = Null).
It seems there are different versions of ASP.NET MVC4 or something like that.
Maybe someone of you know since when this kind of model binding was supported by ASP.NET MVC.
Does my code work for you?
If I change the view models and the lamba expresion to i.e. x=>x.ListName everything works on both computers.
I found the problem. The problem is here:
On my companies machine I had something like this:
The parameter name has to be the same like the name of the complex object
CreateFavoriteListInputModel(case insensitive).Post parameters:
What I don’t understand is why the parameter name matters?
For primitive types this is clear, but for complex types I don’t get it.