【问题标题】:How to use ViewBag to pass list of data from View to controller如何使用 ViewBag 将数据列表从 View 传递到控制器
【发布时间】:2013-05-09 03:44:36
【问题描述】:

如何将视图中的项目列表发送到控制器以保存它。我相信我可以使用 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>
}

和我的控制器

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

         poi = Viewbag.ProductionOrder;

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

     }

【问题讨论】:

    标签: asp.net-mvc viewbag


    【解决方案1】:

    您不能将数据从 ViewBag/ViewData 传递到控制器。它是单向的(控制器查看)。将数据返回到控制器的唯一方法是将其发布(post-body)或在查询字符串中发送。

    事实上,你真的应该尽可能避免使用 ViewBag。它是作为一种便利而添加的,并且与大多数便利方法一样,它经常被滥用。使用视图模型将数据传递给视图并从帖子中接收数据。

    您使用以下方式强输入您的视图:

    @model Namespace.For.My.OrderViewModel
    

    然后,您可以使用 Razor 的 [Foo]For 方法以强类型的方式构建您的字段:

    <div class="editor-label">
        @Html.LabelFor(m => m.ProductionOrderNo);
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(m => m.ProductionOrderNo)
    </div>
    

    最后,在您的发布操作中,您接受视图模型作为参数:

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

    让 MVC 的模型绑定器为您连接发布的数据。

    没有更多的动态。一切都是端到端强类型的,所以如果出现问题,您会在编译时而不是运行时知道。

    【讨论】:

    • 你的意思是
      ??
    • 不,我没有模型,我正在处理放置在引用中的 Dll 文件
    • 没关系,你仍然可以有一个视图模型。它只是一个类,但与数据库或其他数据存储无关。您的数据可以来自任何地方。您只需使用您获取的数据实例化“视图模型”类,然后将该类发送到视图,而不是将所有动态指标都扔进ViewBag
    猜你喜欢
    • 1970-01-01
    • 2020-10-18
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多