2013-05-14 40 views
1

如何從視圖中將一列項目傳遞給控制器​​以進行保存。我相信我可以使用Viewbag,但我真的不知道如何使用ite來將數據從視圖傳遞到控制器。如何使用ViewBag將View中的數據列表傳遞給控制器​​

這是我曾嘗試 我的觀點

@using (Html.BeginForm()) { 
@Html.ValidationSummary(true) 
<fieldset> 
    <legend>ProductionOrderItem</legend> 


    <div class="editor-label"> 
     @Html.Label("ProducrionOrderNo"); 
    </div> 
    <div class="editor-field"> 
     @Html.TextBox("ProductionOrderNo", ViewBag.ProductionOrder as int) 

    </div> 

    <div class="editor-label"> 
     @Html.Label("OrderName") 
    </div> 
    <div class="editor-field"> 
     @Html.TextBox("OrderName", ViewBag.ProductionOrder as string) 
    </div> 
<div class="editor-label"> 
     @Html.Label("OrderDate") 
    </div> 
    <div class="editor-field"> 
     @Html.TextBox("OrderDate", ViewBag.ProductionOrder as DateTime) 
</div> 
     <p> 
     <input type="submit" value="Create" /> 
    </p> 
</fieldset> 
} 

和我的控制器

[HttpPost] 
    public ActionResult Create(FormCollection collection) 
    { 
     ProductionRegistration pr = new ProductionRegistration(); 
     ProductionItem poi = new ProductionItem(); 

     poi = Viewbag.ProductionOrder; 

     pr.SaveOrder(Conn, poi); 
     return RedirectToAction("Index"); 

    } 

回答

5

不能從ViewBag傳遞數據/的ViewData 控制器。這是單向的(控制器查看)。將數據返回給控制器的唯一方法是將其發佈(後主體)或將其發送到查詢字符串中。

事實上,你應該儘量避免使用ViewBag。它被添加爲方便和最便利的方法一樣,它經常被濫用。使用視圖模型將數據傳遞給視圖並接受來自帖子的數據。

你強鍵入你的觀點:

@model Namespace.For.My.OrderViewModel 

然後,您可以使用剃刀的[Foo]For方法來建立自己的領域中一個強類型的方式:

最後,在你的帖子動作,你接受視圖模型作爲參數:

[HttpPost] 
public ActionResult Create(OrderViewModel model) 
{ 
    ... 
} 

並讓MV C的模型綁定器爲您發佈發佈的數據。

沒有更多的動態。一切都是強類型的端到端,所以如果出現問題,你會在編譯時間而不是運行時間知道它。

+0

你是指

?? –

+0

不,我沒有modell,即時通訊工作的Dll文件放置在引用 –

+0

沒關係,你仍然可以有一個*視圖模型*。這只是一個類,但不是綁定到數據庫或其他數據存儲。您的數據可以來自任何地方。您只需使用您獲取的數據實例化「視圖模型」類,然後將該類發送到視圖,而不是將所有動態度量都扔到「ViewBag」中。 –

相關問題