I can bind to properties in ViewModel quite simply like this:
<%=Html.RadioButtonFor(m => m.isCool, true%>cool<br/>
<%=Html.RadioButtonFor(m => m.isCool, false)%>not cool<br/>
but what if I want to bind collection elements in the ViewModel. I am not sure if this is possible. Here is what I have:
My ViewModel:
namespace MvcApplication3.ViewModels
{
public class cpApprovalViewModel
{
public class PersonImage
{
public bool isApproved { get; set; }
public bool isProFilePic { get; set; }
public string uriId { get; set; }
public string urlPath { get; set; }
}
public string displayName { get; set; }
public bool isCool { get; set; }
public List<PersonImage> personImages { get; set; }
}
}
My controller:
public class cpApprovalController : Controller
{
public ActionResult Index()
{
cpApprovalViewModel viewModel = new cpApprovalViewModel();
viewModel.displayName = "jon doe";
viewModel.personImages = new List<cpApprovalViewModel.PersonImage>()
{
new cpApprovalViewModel.PersonImage(){isApproved = false, uriId = "1", isProFilePic = false, urlPath="someImagePath1.jpg" },
new cpApprovalViewModel.PersonImage(){isApproved = false, uriId = "2", isProFilePic = false, urlPath="someImagePath2.jpg" },
new cpApprovalViewModel.PersonImage(){isApproved = false, uriId = "3", isProFilePic = false, urlPath="someImagePath2.jpg" }
};
return View(viewModel);
}
[HttpPost]
public void formReceiver(cpApprovalViewModel viewModel)
{
}
}
My view:
<%: Model.displayName %><br /><br />
<% using (Html.BeginForm("formReceiver", "cpApproval", FormMethod.Post )){ %>
<% foreach (var anImage in Model.personImages){ %>
<%: Html.RadioButtonFor(model => model.personImages.Single(i => i.uriId == anImage.uriId), true, new { id = anImage.uriId })%> Approve <br />
<%: Html.RadioButtonFor(model => model.personImages.Single(i => i.uriId == anImage.uriId), false, new { id = anImage.uriId })%> Deny <br />
<hr />
<% } %>
<input type="submit" value="Save" />
<%} %>
I get the following error: Templates can only be used with access to a field, access to resources, an index of a one-dimensional array, or one-parameter expressions of a custom indexer.
Am I trying to do something impossible here? I hope this makes sense. Thank.