I know there are a lot of posts out there regarding this, most of which I have read and tried all morning but still can't get it working.
I have a view model as such:
namespace GrantTracker.ViewModels
{
public class CoverPageViewModel
{
public List<Compliance> Compliances { get; set; }
}
}
I have a partial view that uses the view model:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<GrantTracker.ViewModels.CoverPageViewModel>" %>
<%
for (var i = 0; i < Model.Compliances.Count; i++)
{ %>
<%=Html.HiddenFor(x => x.Compliances[i].ComplianceId) %>
<%=Html.TextBoxFor(x => x.Compliances[i].ComplianceName) %>
<% } %>
This properly displays the text boxes and their values:
The generated source looks ok to me:
<input id="Compliances_0__ComplianceId" name="Compliances[0].ComplianceId" type="hidden" value="1" />
<input id="Compliances_0__ComplianceName" name="Compliances[0].ComplianceName" type="text" value="Human Subjects" />
<input id="Compliances_1__ComplianceId" name="Compliances[1].ComplianceId" type="hidden" value="2" />
<input id="Compliances_1__ComplianceName" name="Compliances[1].ComplianceName" type="text" value="Vertebrate Animals" />
<input id="Compliances_2__ComplianceId" name="Compliances[2].ComplianceId" type="hidden" value="3" />
<input id="Compliances_2__ComplianceName" name="Compliances[2].ComplianceName" type="text" value="Hazardous Substances" />
When I submit the page the textbox properties are as far as I can tell properly posted:
Compliances[0].ComplianceId:1
Compliances[0].ComplianceName:Human Subjects
Compliances[1].ComplianceId:2
Compliances[1].ComplianceName:Vertebrate Animals
Compliances[2].ComplianceId:3
Compliances[2].ComplianceName:Hazardous Substances
However, the values are all gone when accessed in the controller action
[HttpPost]
public ActionResult SaveCoverPage(CoverPageViewModel coverPageViewModel)
{
return Content(coverPageViewModel.Compliances[0].ComplianceId.ToString());
}
The debugger shows that it knows it should contain three Compliance objects.
However, when drilled down none of them have their values:
Any help with this would be greatly appreciated. I am really stuck on this.
Change your Compliance
class as below.
public class Compliance
{
public int ComplianceId { get; set; }
public string ComplianceName { get; set; }
}
You should define properties correctly.