MVC5 EF6
I have a Product. A product can have multiple Titles, A title has a Type which is an Enum.
I am working on the Create View for a Product - The Model is the Product
View:
@for (int x = 0; x < Model.ProdTitles.Count; x++)
{
<tr>
<td>
@Html.TextBoxFor(model => model.ProdTitles.ToArray()[x].Title, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.ProdTitles.ToArray()[x].Title, "", new { @class = "text-danger" })
</td>
<td>
@Html.EnumDropDownListFor(model => model.ProdTitles.ToArray()[x].TitleTypeID, new { @class = "form-control" })
</td>
<td>
@Html.EnumDropDownListFor(model => model.ProdTitles.ToArray()[x].CultureID, new { @class = "form-control" })
</td>
</tr>
}
In the Controller - when I create a product to return to the view, I create one title for each title type and add it to the product. The view displays everything as I expect.
When I hit the Create button, the product and the titles are returned to the controller as expected and I validate the titles (different validation depending on the type). I add any errors to the ModelState and therefore, ModelState.IsValid is false.
I return back to the View return View(product);
Debugging this product, all the titles are in the product and they all still have their correct types but the View now displays the first Enum in the list, for all titles and not the one that is actually in the model!
If I change the EnumDropDown to a text box, the correct type is displayed, so the model is definitely correct:
I'm not sure why this is happening and I hope someone can suggest a fix? Is it a bug in the EnumDropDownFor? or am I doing something wrong?
Controller code:
public ActionResult Create()
{
Product product = new Product();
foreach (var enm in Utils.Enums.EnumHelper.GetValues<Utils.Enums.TitleType>())
{
product.ProdTitles.Add(new ProdTitle()
{
CultureID = Utils.Enums.CultureID.English_United_Kingdom,
DateCreated = DateTime.Now,
Title = "",
TitleTypeID = enm
});
}
return View(product);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ProdID,DateCreated")] Product product, ICollection<ProdTitle> prodTitles)
{
//ensure titles are all valid before saving
for (int x = 0; x < prodTitles.Count; x++)
{
ProdTitle title = prodTitles.ToArray()[x];
if (!title.IsValid)
{
ModelState.AddModelError(string.Empty, title.TitleTypeID + " title is invalid.");
}
product.ProdTitles.Add(title);
}
if (ModelState.IsValid)
{
db.Products.Add(product);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(product);
}
ProdTitle model
public partial class ProdTitle
{
public long TitleID { get; set; }
public long ProdID { get; set; }
public Utils.Enums.TitleType TitleTypeID { get; set; }
public string Title { get; set; }
public Utils.Enums.CultureID CultureID { get; set; }
public System.DateTime DateCreated { get; set; }
public virtual Product Product { get; set; }
public virtual DataSource DataSource { get; set; }
}