Fad*_*adi 1 asp.net-mvc viewbag
如何从视图中控制项目列表到控制器以保存它.我相信我可以使用Viewbag,但我真的不知道如何使用ite将数据从视图传递到控制器.
这就是我尝试过的观点
@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>
}
Run Code Online (Sandbox Code Playgroud)
和我的控制器
[HttpPost]
public ActionResult Create(FormCollection collection)
{
ProductionRegistration pr = new ProductionRegistration();
ProductionItem poi = new ProductionItem();
poi = Viewbag.ProductionOrder;
pr.SaveOrder(Conn, poi);
return RedirectToAction("Index");
}
Run Code Online (Sandbox Code Playgroud)
您无法将数据从ViewBag/ViewData 传递到控制器.它只是单向的(控制器可以查看).将数据返回到控制器的唯一方法是发布它(后体)或以查询字符串发送它.
实际上,你应该尽可能地避免使用ViewBag.它被添加为方便和大多数便利方法,它经常被滥用.使用视图模型将数据传递到视图并从帖子接收数据.
您强烈键入您的视图:
@model Namespace.For.My.OrderViewModel
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用[Foo]ForRazor 的方法以强类型方式构建字段:
<div class="editor-label">
@Html.LabelFor(m => m.ProductionOrderNo);
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.ProductionOrderNo)
</div>
Run Code Online (Sandbox Code Playgroud)
最后在您的帖子操作中,您接受视图模型作为参数:
[HttpPost]
public ActionResult Create(OrderViewModel model)
{
...
}
Run Code Online (Sandbox Code Playgroud)
让MVC的模型绑定器为您发布已发布的数据.
没有更多动态.一切都是强类型的端到端,所以如果出现问题,你会在编译时知道它,而不是运行时.
| 归档时间: |
|
| 查看次数: |
11239 次 |
| 最近记录: |