如何使用ViewBag将数据列表从View传递到控制器 [英] How to use ViewBag to pass list of data from View to controller
问题描述
如何将视图中的项目列表感知到控制器以进行保存.我相信我可以使用Viewbag,但我真的不知道如何使用ite将数据从视图传递到控制器.
how can i sen a list of items from a view to a controller to save it. i believe that i can use Viewbag but i dont realy no how to use ite to pass data from view to controller.
这就是我尝试过的我的观点
this is what i have tried My 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");
}
推荐答案
您不能将数据从ViewBag/ViewData 传递给控制器.它仅是单向的(控制器可查看).将数据返回到控制器的唯一方法是将其发布(后正文)或随同查询字符串一起发送.
You can't pass data from ViewBag/ViewData to the controller. It's one-way only (controller to view). The only way to get data back to the controller is to post it (post-body) or send it along in a querystring.
实际上,您实际上应该尽可能避免使用ViewBag.它是作为一种便利添加的,并且像大多数便利方法一样,经常被滥用.使用视图模型既可以将数据传递到视图,也可以从帖子中接受数据.
In fact, you should really avoid ViewBag as much as possible. It was added as a convenience and like most convenience methods, it's abused more often than not. Use a view model to both pass data to the view and accept data back from a post.
您可以通过以下方式强烈键入您的观点:
You strongly-type your view with:
@model Namespace.For.My.OrderViewModel
然后,您可以使用Razor的 [Foo] For
方法以强类型方式构建字段:
Then, you can use the [Foo]For
methods of Razor to build your fields in a strongly-typed way:
<div class="editor-label">
@Html.LabelFor(m => m.ProductionOrderNo);
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.ProductionOrderNo)
</div>
最后在发布操作中,您将视图模型作为参数:
And finally in your post action, you accept the view model as a param:
[HttpPost]
public ActionResult Create(OrderViewModel model)
{
...
}
然后让MVC的modelbinder为您连接发布的数据.
And let MVC's modelbinder wire up the posted data for you.
没有更多动态.一切都是端到端的强类型,因此如果出现问题,您将在编译时而不是运行时知道它.
No more dynamics. Everything is strongly-typed end-to-end, so if something goes wrong, you'll know it at compile-time, not run-time.
这篇关于如何使用ViewBag将数据列表从View传递到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!