2010-11-08 76 views
3

在我可以綁定到的屬性在視圖模型相當簡單,像這樣:asp.net mvc。視圖模型綁定到項目集合

<%=Html.RadioButtonFor(m => m.isCool, true%>cool<br/> 
<%=Html.RadioButtonFor(m => m.isCool, false)%>not cool<br/> 

,但如果我想綁定到視圖模型中收集的物品是什麼。我不確定是否有可能。下面是我有:

我的視圖模型:

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" /> 
<%} %> 

,我發現了以下錯誤: 模板可以僅用於字段訪問,屬性訪問,單維數組索引或單參數自定義索引器表達式。

我想在這裏做一些不可能的事嗎?我希望這是有道理的。謝謝。

回答

1

是的 - 你想做什麼是可能的。

我認爲你的問題是你試圖在foreach循環中使用.Single再次獲取相關圖像。

嘗試改變:

<%: 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

+0

RPM,謝謝!您的代碼無法正常工作,但該鏈接確實有效!我不能相信我錯過了這一點。我認爲它必須在一個「for」循環中才能發揮作用。 – RayLoveless 2010-11-09 01:55:32