2011-12-01 176 views
6

我有一個Viewbag,它是從Controller傳遞給View的列表。 Viewbag是我的案例中的10條記錄的列表。一旦進入視圖,如果用戶點擊保存,我喜歡將視圖的內容傳遞給[HttpPost]創建控制器,以便我可以創建Viewbag中的記錄。我確信如何做到這一點。我已經爲1個項目創建了新記錄,但是如何爲多個記錄創建記錄。MVC將ViewBag傳遞給控制器​​

回答

12

這是一個使用ViewBag的快速示例。我會建議切換和使用模型來做綁定。這是一篇很棒的文章。 Model Binding

獲取方法:

public ActionResult Index() 
    { 
     ViewBag.Message = "Welcome to ASP.NET MVC!"; 
     List<string> items = new List<string>(); 
     items.Add("Product1"); 
     items.Add("Product2"); 
     items.Add("Product3"); 

     ViewBag.Items = items; 
     return View(); 
    } 

POST方法

[HttpPost] 
    public ActionResult Index(FormCollection collection) 
    { 
     //only selected prodcuts will be in the collection 
     foreach (var product in collection) 
     { 

     } 
     return View(); 
    } 

HTML:

@using (Html.BeginForm("Index", "Home")) 
{ 
    foreach (var p in ViewBag.Items) 
    { 
     <label for="@p">@p</label> 
     <input type="checkbox" name="@p" /> 
    } 

    <div> 
    <input id='btnSubmit' type="submit" value='submit' /> 
    </div> 
}