I got above subjected error while POST the form and I think the root cause of subjected error is "DropDownListFor", where plural SelectList twice called, If Yes, please suggest the solution?
If I change from "x=>x.Values" to "x=>x.Name" then also get error "There is no ViewData item of type 'IEnumerable' that has the key 'DDLView.Name'."
Editor Template
@model DropDownListViewModel
@Html.LabelFor(x=>x.Values, Model.Label)
@Html.DropDownListFor(x=>x.Values, Model.Values)
View Model
public class HomePageViewModel
{
public DropDownListViewModel DDLView { get; set; }
}
public class DropDownListViewModel
{
public string Label { get; set; }
public string Name { get; set; }
public SelectList Values { get; set; }
}
Controller
public ActionResult Index()
{
HomePageViewModel homePageViewModel = new HomePageViewModel();
homePageViewModel.DDLView = new DropDownListViewModel
{
Label = "drop label1",
Name = "DropDown1",
Values = new SelectList(
new[]
{
new {Value = "1", Text = "text 1"},
new {Value = "2", Text = "text 2"},
new {Value = "3", Text = "text 3"},
}, "Value", "Text", "2"
)
};
}
[HttpPost]
public ActionResult Index(HomePageViewModel model)
{
return View(model);
}
View
@model Dynamic.ViewModels.HomePageViewModel
@using (Html.BeginForm())
{
@Html.EditorFor(x=>x.DDLView)
<input type="submit" value="OK" />
}
The problem is that SelectList doesn't have parameterless constructor and model binder can't instantiate it, but you are trying to post it back.
To solve your problem change 2 things in your implementation:
1) Change in your editor template
@Html.DropDownListFor(x=>x.Values, Model.Values)
to
@Html.DropDownListFor(x=>x.ValueId, Model.Values)
2) add next to your original DropDownListViewModel
[ScaffoldColumn(false)]
public string ValueId { get; set; }
Now your post action parameter will be populated with correct values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With