我可以像这样简单地绑定到ViewModel中的属性:
<%=Html.RadioButtonFor(m => m.isCool, true%>cool<br/>
<%=Html.RadioButtonFor(m => m.isCool, false)%>not cool<br/>
但如果我想绑定到ViewModel中的集合项,该怎么办?我不确定是否可能。这就是我所拥有的:
我的ViewModel:
namespace MvcApplication3.ViewModels
{
public class cpApprovalViewModel
{
// My internal class
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; }
}
}
我的控制器:
public class cpApprovalController : Controller
{
//
// GET: /cpApproval/
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);
}
//cpApprovalViewModel viewModel
[HttpPost]
public void formReceiver(cpApprovalViewModel viewModel)
{
// This is where I'd like to get access to the changed personImages (approved/disapproved )
}
}
我的观点:
<%: 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" />
<%} %>
我收到以下错误: 模板只能用于字段访问,属性访问,单维数组索引或单参数自定义索引器表达式。
我想在这里做一些不可能做的事吗?我希望这是有道理的。感谢。
答案 0 :(得分:1)
是的 - 您尝试做的事情是可能的。
我认为您的问题是,当您已经在.Single
循环中拥有该项时,您尝试使用foreach
再次获取相关图像。
尝试更改:
<%: Html.RadioButtonFor(model => model.personImages.Single(i => i.uriId == anImage.uriId), true, new { id = anImage.uriId })%> Approve <br />
要:
<%: Html.RadioButtonFor(model => anImage, true, new { id = anImage.uriId })%> Approve <br />
有关模型绑定到集合here的更多信息。