asp.net-mvc ASP.NET MVC 中的嵌套表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1556986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:53:59  来源:igfitidea点击:

Nested forms in ASP.NET MVC

asp.net-mvc

提问by Thomas

I have a shopping cart where the following are true:

我有一个购物车,其中符合以下条件:

  • There is one "Remove" button for each product in the shopping cart
  • There is one editable quantity text box for each product in the shopping cart
  • There is one "Update" button for the entire shopping cart
  • 购物车中的每个产品都有一个“移除”按钮
  • 购物车中的每个产品都有一个可编辑的数量文本框
  • 整个购物车有一个“更新”按钮

The idea is that the user can modify the quantities for each product in the cart and click "Update" to commit the changes.

这个想法是用户可以修改购物车中每个产品的数量,然后单击“更新”以提交更改。

How would you program the "Update" button using MVC? Would you wrap the entire shopping cart in a form that posts back to itself and somehow locate the quantity values in the FormCollection? The problem with that approach is that since the "Remove" buttons each live in their own forms I would now be doing nested forms on the page and I am not even sure that is allowed.

您将如何使用 MVC 对“更新”按钮进行编程?您是否会将整个购物车包装在一个表单中,该表单可以回传给自己,并以某种方式在 FormCollection 中找到数量值?这种方法的问题在于,由于每个“删除”按钮都以自己的形式存在,我现在将在页面上进行嵌套表单,我什至不确定是否允许这样做。

        <% using (Html.BeginForm("Index", "Cart")) { %> 
        <table>
            <tr>
                <th>&nbsp;</th>
            </tr>
        <% foreach (var item in Model) { %>
            <tr>
                <td>
                    <input name="qty" type="text" value="<%=item.Quantity%>" maxlength="2" />
                    <% using (Html.BeginForm("RemoveOrderItem", "Cart")) { %>                       
                        <%= Html.Hidden("ShoppingCartItemID", item.ShoppingCartItemID) %>
                        <input name="add" type="submit" value="Remove" />
                    <%} %>
                </td>
            </tr>
        <% } %>
        </table>

        <input name="update" type="submit" value="Update" />
        <%} %>  

How would I incorporate the bottom input into this form?

我如何将底部输入合并到此表单中?

采纳答案by Chris Missal

We've done this on our project by using an individual form for Remove, and a completely different form for Update. They both go to different POST actions in the CartController.

我们在我们的项目中通过使用单独的表单删除和完全不同的更新表单来完成此操作。它们都转到 CartController 中的不同 POST 操作。

UPDATE: Example given (in raw HTML):

更新:给出的示例(在原始 HTML 中):

<form action="/cart/updatequantity" method="post"> 
    <input type="hidden" name="ProductSku" value="ABC-123" /> 
    <input name="quantity" class="quantity" size="2" maxlength="2" type="text" value="1" /> 
    <input type="submit" value="Update" /> 
</form> 

<form action="/cart/removeitem" method="post"> 
    <input type="hidden" name="productSku" value="ABC-123" /> 
    <input type="submit" value="Remove" /> 
</form> 

回答by Thomas

Nested forms are explicitly not supported in HTML.

HTML 明确不支持嵌套表单。

You can however have multiple forms, this is allowed. Wrap each product in a separate form, add a product-specific parameter to each form post url so that you know in the respective controller action which product needs to be updated.

但是,您可以有多种形式,这是允许的。将每个产品包装在一个单独的表单中,向每个表单发布 url 添加一个特定于产品的参数,以便您在相应的控制器操作中知道哪个产品需要更新。

Something like this:

像这样的东西:

<form action="/update/21342345">
</form>

How would I incorporate the bottom input into this form?

我如何将底部输入合并到此表单中?

Two options:

两种选择:

  1. Give each form its own submit button. Call it something like "Update this product". You will specify which one to update in the url parameter.
  2. Wrap you complete generated table along with the submit button into one single form. When submitted, you will need to update all of the products contained in the form. or somehow detect which ones were changes and only update those.
  1. 为每个表单提供自己的提交按钮。称之为“更新此产品”。您将在 url 参数中指定要更新的内容。
  2. 将您生成的完整表格与提交按钮包装成一个表单。提交后,您需要更新表单中包含的所有产品。或者以某种方式检测哪些是更改并只更新那些。

Advice applies to both buttons, submit and delete. You can specify the task in the post url, like:

建议适用于提交和删除两个按钮。您可以在帖子 url 中指定任务,例如:

action="/update/21342345"

or

或者

action="/delete/21342345"

回答by LukLed

I am using jQuery in similar situation. Remove button calls post() method and if it succeeds, div element of this product is removed from page (remove() method). Update can be submit of normal form. you can also use jQuery to program ajax Update method and then load shopping cart dynamically, without having to reload whole page (by $().html() method called in callback of post()).

我在类似的情况下使用 jQuery。移除按钮调用 post() 方法,如果成功,则从页面中移除该产品的 div 元素(remove() 方法)。更新可以通过普通形式提交。您还可以使用 jQuery 编写 ajax Update 方法,然后动态加载购物车,而无需重新加载整个页面(通过 post() 回调中调用的 $().html() 方法)。

Remove could look like:

删除可能看起来像:

onclick="if (confirm('Please confirm.')) $.post('/Cart/Remove/63',{},function(data) { if (data == 'ok') {$('#cart-element-63').remove())";

onclick="if (confirm('请确认。')) $.post('/Cart/Remove/63',{},function(data) { if (data == 'ok') {$('#cart -element-63').remove())";

回答by Adrian

I was looking for the same tip, and found this post. I've just done this using named submit buttons for the delete buttons, and unique quantity text field names.

我正在寻找相同的提示,并找到了这篇文章。我刚刚使用删除按钮的命名提交按钮和唯一数量文本字段名称完成了此操作。

A single form wraps the entire cart. The primary submit button would be the update cart button. Each remove item button is named "remove" with a value set to a unique key of that cart item.

一个表格包裹了整个购物车。主要提交按钮将是更新购物车按钮。每个删除项目按钮都命名为“删除”,其值设置为该购物车项目的唯一键。

<input class="btnRemove" name="remove" type="image" value="@item.ProductId" />

Each Quantity text field is prefixed "qnty-" with the unique key for that cart item.

每个 Quantity 文本字段都以“qnty-”为前缀,并带有该购物车项目的唯一键。

<input id="[email protected]" name="[email protected]" type="text" value="@item.Quantity" class="cartListQty" />

Once submitted my action loops through a FormCollection. If the name is "remove", I remove that unique key from the cart. If the name starts with "qnty-" I get the remainder of the name (the unique cart item key) and adjust that items quantity to the value of the text field.

提交后,我的操作将通过 FormCollection 循环。如果名称是“remove”,我会从购物车中删除该唯一键。如果名称以“qnty-”开头,我会得到名称的其余部分(唯一的购物车项目键)并将该项目数量调整为文本字段的值。

[HttpPost]
public ActionResult Index(FormCollection collection)
{
Cart myCart = cartRepo.LoadCart();
foreach (string item in collection.AllKeys)
{
    if (item.StartsWith("qnty-"))
    {
    int productId = Convert.ToInt32(item.Substring(5));
    // Adjust quantity
    }
    if (item == "remove") // Remove item from cart
}
cartRepo.Save();
return RedirectToAction("Index");
}