未能从视图中的数据传递受到Html.BeginForm行动() [英] Failing to pass data from view to the Action by Html.BeginForm()

查看:120
本文介绍了未能从视图中的数据传递受到Html.BeginForm行动()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在asp.net mvc的非常新,所以我的失败可能是基本的东西,以及背后的原因,但我似乎无法找到它经过近天现在的工作。

I am very new at asp.net mvc, so the reason behind my failure might be something basic as well, but I can't seem to find it after nearly a days work now.

我所试图做的是从索引视图得到编辑的模型,并将其传递给第二个动作不具有视图并返回返回 RedirectToAction(「指数」)中相关的控制器。在 OrdersItemsController 我的行动是为以下内容:

What I am trying to do is to get the edited Model from the Index view and pass it to a second action which does not have view and returns return RedirectToAction("Index") in the related controller. In OrdersItemsController my Action is as the following:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult MarkedShipped(IEnumerable<orders_items> orderItems)
{
    if (ModelState.IsValid)
    {
        foreach (var item in orderItems)
        {
            unitOfWork.GenericRepository<orders_items>().Update(item);
        }
    }
    return RedirectToAction("Index");
}

而在Index.cshtml这是OrdersItems文件夹中的意见,我所做的是如下:

And in the Index.cshtml which is in OrdersItems folder in the Views, what I did is as following:

@model IEnumerable<Project.DataAccess.orders_items>
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@using (Html.BeginForm("MarkedShipped", "OrdersItems", new { orderItems = Model }))
{

    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.quantity)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.itemprice)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.trackingnumber)
            </th>
        </tr>

        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.quantity)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.itemprice)
                </td>
                <td>
                    @Html.EditorFor(modelItem => item.trackingnumber)
                </td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new { id = item.itemid })
                </td>
            </tr>

        }
    </table>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="MarkShipped" class="btn btn-default" />
        </div>
    </div>
}

我的问题是,我不能够从参数的OrderItems的观点得到了示范,我不知道这是否是正确的语法获得什么,我试图完成;但我得到的OrderItems 时的动作被称为是 orders_items 的列表,包括计数= 0 不是空值。

My problem is, I am not able to get the Model from the view with orderItems parameter, I am not sure if this is the right "syntax" for what I am trying to accomplish; but what I get for orderItems when the action is called is a List of orders_items with Count = 0 not a null value.

我还检查是否有一个应用程序级的异常,但在的Global.asax 的Application_Error >

I have also checked if there is an application level exception, but got no exception from Application_Error in Global.asax

我被困了一天现在这么如果有人能指出我如何模型(或编辑的数据)传递给动作对我来说,更新dB的方向,我将非常感激。谢谢你。

I am stuck for a day now so If anyone can point me a direction on how to pass the Model (or "the edited data") to the action for me to update the db, I would be very grateful. Thanks.

推荐答案

首先,你不能添加一个模型,它是一个集合(或其中包含一个属性,它是一个复杂的对象或集合的模型),以一个方式的路由参数。内部辅助调用的ToString()方法,如果你检查你的表单标签生成的HTML,你会看到类似

Firstly you cannot add a model which is a collection (or a model which contains a property which is a complex object or collection) to a forms route parameters. Internally the helper calls the .ToString() method and if you inspect the html generated for your form tag you will see something like

<form action=OrdersItems/MarkedShipped?orderItems=System.Collection.Generic.......

和绑定操作将失败,因为你收集不能被绑定到一个字符串。即使没有工作,这将是相当没有意义的,因为它只是回来后模型的初始值。

and binding will fail since you collection cannot be bound to a string. Even if it did work, it would be rather pointless because it would just post back the original values of the model.

接下来,您不能使用的foreach 循环生成表单控件。同样,如果你检查HTML的产生,你会看到 EditorFor()方法生成具有重复输入 ID 属性(无效HTML)和重复名称属性不具备必要的索引当您发布绑定到一个集合。您需要使用自定义的是循环 EditorTemplate 为typeof运算 orders_items

Next, you cannot use a foreach loop to generate form controls. Again if you inspect the html your generating you will see that the EditorFor() method is generating inputs with duplicate id attributes (invalid html) and duplicate name attributes which do not have the necessary indexers to bind to a collection when you post. You need to use either a for loop of a custom EditorTemplate for typeof orders_items

使用循环意味着你的模型必须实施的IList&LT; T&GT; 和视图必须

Using a for loop means that your model must implement IList<T> and the view needs to be

@model IList<Hochanda.CraftsHobbiesAndArts.DataAccess.orders_items>
@using (Html.BeginForm()) // only necessary to add the controller and action if they differ from the GET method
{
  ....
  @for(int i = 0; i < Model.Count; i++)
  {
    @Html.DisplayFor(m => m[i].quantity)
    ....
    @Html.EditorFor(m => m[i].trackingnumber)
  }
  ....
}

使用 /Views/Shared/EditorTemplates/orders_items.cshtml EditorTemplate ,创建一个部分(注意该文件的名称必须与类的名称相匹配)

Using an EditorTemplate, create a partial in /Views/Shared/EditorTemplates/orders_items.cshtml (note the name of the file must match the name of the class)

@model Hochanda.CraftsHobbiesAndArts.DataAccess.orders_items
<tr>
  <td>@Html.DisplayFor(m => m.quantity)</td>
  ....
  <td>@Html.EditorFor(m => m.trackingnumber)</td>
  ....
</tr>

,然后在主视图(可以使用的IEnumerable&LT; T&GT;

@model IEnumerable<Hochanda.CraftsHobbiesAndArts.DataAccess.orders_items>
@using (Html.BeginForm())
{
  <table class="table">
    <thead>
      ....
    <thead>
    <tbody>
      @Html.EditorFor(m => m)
    </tbody>
  </table>
  ....
}

EditorFor()方法接受的IEnumerable&LT; T&GT; ,并会为每个项目一行在你收集基于HTML的 EditorTemplate

The EditorFor() method accepts IEnumerable<T> and will generate one row for each item in you collection based on the html in the EditorTemplate

在这两种情况下,它检查你的HTML,你会看到现在的正确名称属性必要您模型,当你绑定发布

In both cases, it you inspect the html you will now see the correct name attributes necessary for you model to bind when you post

<input type="text" name="[0].trackingnumber" ... />
<input type="text" name="[1].trackingnumber" ... />
<input type="text" name="[3].trackingnumber" ... />

这篇关于未能从视图中的数据传递受到Html.BeginForm行动()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆