2013-07-09 99 views
1

的列表屬性我已經示範綁定到模型

public class FooContainer 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public IList<Foo> Foos { get; set; } 
} 

public class Foo 
{ 
    public string Name {get; set; } 
    public string Description {get; set;} 
} 

以下實施例控制器

public class FooController : Controller 
{ 
    public ActionResult Index(){ 
     return View(new FooContainer()); 
    } 

    [HttpPost] 
    public ActionResult Index(FooContainer model){ 
     //Do stuff with the model 
    } 
} 

我想創建一個視圖,其使用戶能夠CRUD FOOS。

現有的研究

我已閱讀以下內容:
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

與SO下面的文章以及
MVC4 Allowing Users to Edit List Items
MVC4 bind model to ICollection or List in partial

,所以我知道如何通過一個IEnumerable <>來回,問題是,我想通過一些容器,與包括一個IEnumerable <>

要求
我希望能夠綁定到這個複雜模型的其他屬性使其完全通過並全部傳遞給控制器​​。假設控制器不做任何事情,只是渲染視圖並在後期接收FooController模型。此外,我想要任何相關的文章或引用視圖語法需要啓用此。

在此先感謝

+0

嘿,請在FooController中描述一種方法。 –

+0

也許它可以幫助:谷歌'mvc4定製粘合劑' –

+0

我正在調查MVC4定製粘合劑現在...他們看起來挺酷! –

回答

2

這應該讓你開始。

你的模型:

public class FooContainer 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public IList<Foo> Foos { get; set; } 
} 

public class Foo 
{ 
    public string Name {get; set; } 
    public string Description {get; set;} 
} 

控制器操作:

[HttpGet] 
public ActionResult Foo() 
{ 
    var model = new FooContainer(); 
    return View("Foo", model); 
} 

[HttpPost] 
public ActionResult Foo(FooContainer model) 
{ 
    ViewBag.Test = m.Foos[1].Name; 
    return View("Foo", model); 
} 

您的看法:

@model DriveAway.Web.Models.FooContainer 

@using(Html.BeginForm()) 
{ 
    <p>@Html.TextBoxFor(m => m.ID)</p> 
    <p>@Html.TextBoxFor(m => m.Name)</p> 

    for (int i = 0; i < 5; i++) 
    { 
     <p>@Html.TextBoxFor(m => m.Foos[i].Name)</p> 
     <p>@Html.TextBoxFor(m => m.Foos[i].Description)</p> 
    } 

    <button type="submit">Submit</button> 

} 

@ViewBag.Test 

這裏會發生什麼事是,當你按下提交,i列表將被髮送到你的HttpPost Foo()動作,你可以隨心所欲地做任何事情。在我的示例中,它會顯示輸入到第二個名稱文本框中的內容。你顯然可以遍歷每個值並檢查是否填寫等。

foreach (var f in m.Foos) 
    if (!string.IsNullOrEmpty(f.Name) && !string.IsNullOrEmpty(f.Description)) 
     addToDB(f); // some method to add to to a database 

在視圖中,我用一個for loop是5。限制,但顯然這是給你。

+0

嗨Rudeovski,我不知道這是我之後,我會看看。我不知道這將如何傳回整個容器,它看起來會傳回一個IEnumerable 到控制器(我已經可以工作了)。我想通過複雜的模型,而不僅僅是一個列表。 –

+0

它會將整個FooContainer傳回。我已將其他兩個屬性添加到視圖中。所以在提交時,它會從FooContainer傳入ID和名稱,以及Foos列表。 – jzm