2011-02-14 58 views
0

我在這裏遇到的困難是如何做「如何做零件?」部分?綁定列表難度

namespace MvcApplication1.Models 
{ 
    public class Test { public Test() 
    { 
     Name = "Test"; 
     Subs = new List<Sub>(); 
     Subs.Add(new Sub { Num = 1, SubName = "A", Valid=false }); 
     Subs.Add(new Sub { Num = 2, SubName = "B" , Valid= true}); } 
     public string Name { get; set; } 
     public List<Sub> Subs { get; set; } 
    } 
    public class Sub { 
     public int Num { get; set; } 
     public string SubName { get; set; } 
     public bool Valid { get; set; } 
    } 

} 

查看:

@model MvcApplication1.Models.Test 

@{ 
    View.Title = "Index"; 
    Layout = "~/Views/Shared/_Layout.cshtml"; 
} 

@{ 
    var i = 0; 
    } 
} 

    <h2>Test2</h2> 
    @using (Html.BeginForm()) 
    {  
     <p>Test Name</p>@Html.EditorFor(m => m.Name) 
     foreach(var item in Model.Subs)  
     <p>Sub 1</p> 


     @Html.EditorFor(m => item[i].Num)<------ 
      @Html.EditorFor(m => item[i].SubName**)<------How to do this part?**  
     @Html.EditorFor(m => item[i++].Valid**) 



     <input type="submit" value="Save" /> 
    } 

控制器:

public ActionResult Index() 
    { 
     Test test = new Test(); 
     return View(test); 
    } 

    [HttpPost] 
    public ActionResult Index(Test test) 
    { 
     return View(test); 
    } 

} 
+0

你沒有解釋你期望顯示的子名稱?!在我意識到這一點之前,我最終寫了一半的答案。請添加一個更清晰的解釋你需要什麼? – gideon 2011-02-14 07:32:19

回答

0

你可以自定義編輯模板:

@using (Html.BeginForm()) 
{  
    <p>Test Name</p> 
    @Html.EditorFor(m => m.Name) 
    @Html.EditorFor(m => m.Subs) 
    <input type="submit" value="Save" /> 
} 

和相應的模板編輯器裏面(~/Views/Home/EditorTemplates/Sub.cshtml) :

@model MvcApplication1.Models.Sub 
@Html.EditorFor(m => m.Num) 
@Html.EditorFor(m => m.SubName) 
@Html.EditorFor(m => m.Valid)