Is there any way to bind the value of a DropDownListFor
in the context of a list of child models ?
Currently if I have a Parent model that has a list of child models that are looped over, the DropDownListFor HtmlHelper
won't bind the value.
I created a case on dotnetfiddle to explain this : https://dotnetfiddle.net/RB4UVc
This is the code in the fiddle copied here:
Model.cs
using System;
using System.Web.Mvc;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace HelloWorldMvcApp
{
public class Model
{
public int? SelectedValue { get; set; }
public List<Value> Values { get; set; }
public IEnumerable<SelectListItem> Fields
{
get
{
return new[]
{
new SelectListItem { Text = "1", Value = "1" },
new SelectListItem { Text = "2", Value = "2" },
new SelectListItem { Text = "3", Value = "3" }
};
}
}
public Model()
{
Values = new List<Value>();
}
}
public class Value
{
public int SelectedValue { get; set; }
public string Name { get; set; }
}
}
HomeController.cs
using System;
using System.Web.Mvc;
using System.Collections.Generic;
namespace HelloWorldMvcApp
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
var model = new Model();
model.SelectedValue = 2;
model.Values.Add(new Value { SelectedValue = 3, Name = "John Doe" });
return View(model);
}
}
}
Index.cshtml
@model HelloWorldMvcApp.Model
<h1>Single</h1>
<p>Value: @Model.SelectedValue</p>
@Html.DropDownListFor(model => model.SelectedValue, Model.Fields)
<hr>
<h1>Collection</h1>
@foreach(var value in Model.Values)
{
<p>Value: @value.SelectedValue</p>
<p>Name: @Html.TextBoxFor(_ => value.Name)</p>
@Html.DropDownListFor(_ => value.SelectedValue, Model.Fields)
}
<hr>
<h1>Indexed Collection</h1>
@for(var i = 0; i < Model.Values.Count(); i++)
{
<p>Value: @Model.Values[i].SelectedValue</p>
<p>Name: @Html.TextBoxFor(model => model.Values[i].Name)</p>
@Html.DropDownListFor(model => model.Values[i].SelectedValue, Model.Fields)
}
The first is using a normal value that binds correctly, the second would be a collection of child models. As we can see, the TextBoxFor
is able to bind correctly the value.
Am I doing something wrong here or is there a workaround for this issue ? (beside building manually a <select>
element)
Side note: I look specifically for this in a context of a loop considering I need to save an array of child models in a batch.