C# 如何在 ASP.NET MVC 中处理同一表单上的编辑和删除按钮?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17662716/
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-08-10 10:07:55  来源:igfitidea点击:

How to handle an edit and delete button on the same form in ASP.NET MVC?

c#asp.net.netasp.net-mvc

提问by Mike Perrenoud

Consider the following markup:

考虑以下标记:

<h2>Edit SAS Program</h2>
@using (Html.BeginForm("Edit", "SasProgram", FormMethod.Post))
{
    <label for="Name">Name</label>
    @Html.TextBoxFor(model => model.Name)

    using (Html.BeginForm("Delete", "SasProgram", FormMethod.Post))
    {
        <input type="submit" class="button" value="Delete" />
    }
    <input type="submit" class="button" value="Save Changes" />
}

I'd like to have the Deletebutton on the same view as the Edit. However, it's not letting me have nested forms. What is the appropriate way to handle this situation?

我希望该Delete按钮与Edit. 但是,它不允许我嵌套表单。处理这种情况的适当方法是什么?

I tried leveraging this answer, How to handle nested forms in ASP.NET MVC, but it's a broken link now.

我尝试利用这个答案,如何处理 ASP.NET MVC 中的嵌套表单,但它现在是一个断开的链接。

采纳答案by Kristof Claes

The best and easiest way would be to use two forms but don't nest them:

最好和最简单的方法是使用两种形式,但不要嵌套它们:

<h2>Edit SAS Program</h2>
@using (Html.BeginForm("Edit", "SasProgram", FormMethod.Post))
{
    <label for="Name">Name</label>
    @Html.TextBoxFor(model => model.Name)

    <input type="submit" class="button" value="Save Changes" />
}

@using (Html.BeginForm("Delete", "SasProgram", FormMethod.Post))
{
    <input type="submit" class="button" value="Delete" />
}

This way you have:

这样你有:

  • Two separate forms
  • No GET requests
  • The delete button below the edit button, which makes more sense when you're on a view that allows you to edit something.
  • 两种不同的形式
  • 没有 GET 请求
  • 编辑按钮下方的删除按钮,当您在允许您编辑某些内容的视图上时,这更有意义。

回答by Matthew Perron

Edit : Here's how to do it with ajax using an HttpPost.

编辑:这是使用 HttpPost 使用 ajax 进行操作的方法。

//
// POST: /Divisions/Delete
[HttpPost, ActionName("Delete"), Authorize]
public ActionResult DeleteConfirmed(int id)
{
    Division division = _db.Divisions.Single(x => x.DivisionId == id);

    string errorMessage;
    if (DbRelationEnforcer.CanDelete(_db, division, out errorMessage))
    {
        division.SetDeleted(User.Identity.Name);
        _db.SaveChanges();
        return Json(new JsonResponseCreatePartial { Success = true }, JsonRequestBehavior.AllowGet);
    }

    return Json(new JsonResponseCreatePartial { Success = false, Message = errorMessage }, JsonRequestBehavior.AllowGet);
}

Then, on the view, you must use the <input type="submit">Save changes</input>to save your changes (within the form), and a simple link/button to delete, like this:

然后,在视图上,您​​必须使用<input type="submit">Save changes</input>来保存您的更改(在表单内),并使用一个简单的链接/按钮进行删除,如下所示:

<h2>Edit SAS Program</h2>
@using (Html.BeginForm("Edit", "SasProgram", FormMethod.Post))
{
    <label for="Name">Name</label>
    @Html.TextBoxFor(model => model.Name)

    <input id='delete-btn' type="button" class="button" value="Delete" />
    <input type="submit" class="button" value="Save Changes" />
}

Finally, you have to use JS to post to your action from the view, when the user clicks on Delete.

最后,当用户单击删除时,您必须使用 JS 从视图发布到您的操作。

<script type='text/javascript'>
    $(function() {
        $("input#delete-btn").click(function(){
            $.post('@Url.Action("Delete")', '@Model.Id', function(data) {
                if(data.Success) {
                    ' ... handle the success case
                } else {
                    ' ... error management
                }
            });
        });
    });
</script>

This will work, but in order to have a better UX, it would be preferable to have the Delete button from the Index/list view, and using a JQuery UI dialog to confirm before doing the ajax post. This will skip having to load the Edit page if/when you want to delete multiple items one after the other.

这会起作用,但为了获得更好的用户体验,最好在索引/列表视图中使用删除按钮,并在执行 ajax 发布之前使用 JQuery UI 对话框进行确认。如果/当您想一个接一个地删除多个项目时,这将跳过必须加载编辑页面。

回答by Rubens Mariuzzo

First, you cannot nest <form>element. The specification doesn't allow it. Since you are using the MVC pattern I have two options that came to my mind:

首先,你不能嵌套<form>元素。规范不允许。由于您使用的是 MVC 模式,因此我想到了两个选项:

  1. You can retain the savebutton as the submit button of the form, and make the deletebutton a HTML link. Then the deletebutton will target to a different route, it could be something like: GET /program/delete/{id}.

  2. You can have two buttons inside the same form, then with JavaScript after clicking one of the buttons you will change the actionattribute of the form.

  1. 您可以保留保存按钮作为表单的提交按钮,并将删除按钮设为HTML 链接。然后删除按钮将定位到不同的路线,它可能是这样的:GET /program/delete/{id}

  2. 您可以在同一个表单中有两个按钮,然后在单击其中一个按钮后使用 JavaScript 更改表单的action属性。

Update

更新

There is a third option, that is more clean: using two submit buttons with same nameattribute and different values.

还有第三个选项,更简洁:使用两个具有相同name属性和不同值的提交按钮。

Your form will have two buttons:

您的表单将有两个按钮:

public ActionResult MyAction(string submitButton) {
    switch (submitButton) {
        case "save":
            // ...
        case "delete":
            // ...
    }
}

For more details check this answer: https://stackoverflow.com/a/443047/439427

有关更多详细信息,请查看此答案:https: //stackoverflow.com/a/443047/439427

回答by nrodic

I would use different values for button name in the same form:

我会以相同的形式为按钮名称使用不同的值:

@using (Html.BeginForm("Edit", "SasProgram", FormMethod.Post))
{
    <label for="Name">Name</label>
    @Html.TextBoxFor(model => model.Name)

    <button name="action" value="delete">Delete</button>
    <button name="action" value="save">Save Changes</button>
}

and then switch in controller:

然后在控制器中切换:

[HttpPost]
public ActionResult Edit( SomeModel model, string action )
{
    switch( action ) {
        case "delete":
            // delete action
            break;
        case "save":
            // save action
            break;
    }
}

The code is written from memory but it works in production. Note that buttons are of default type - submit.

代码是从内存中编写的,但它可以在生产中使用。请注意,按钮是默认类型 - 提交。

回答by Péter

First of all. Every modification request should be use the post method.
I make some R&D and build the basics of a multi submit button handler in a wiki A clean solution to use multiple submit button in ASP.NET MVC.
I think it could solve your problem.

首先。每个修改请求都应该使用 post 方法。
我进行了一些研发,并在 wiki 中构建了多提交按钮处理程序的基础知识在 ASP.NET MVC 中使用多个提交按钮的干净解决方案
我认为它可以解决您的问题。

回答by Ramon Smits

You can also use html 5 feature to target a form from an input button. Below I have created both a delete and save form and have the submit buttons outside of the forms but targeting them via the formattribute.

您还可以使用 html 5 功能从输入按钮定位表单。下面我创建了一个删除和保存表单,并在表单之外设置了提交按钮,但通过form属性将它们作为目标。

I think most browsers support this except IE.

我认为大多数浏览器都支持这个,除了 IE。

No javascript required.

不需要 javascript。

@using (Html.BeginForm("Edit", "SasProgram", FormMethod.Post, new { id = "editForm" }))
{
    <label for="Name">Name</label>
    @Html.TextBoxFor(model => model.Name)
}

@using (Html.BeginForm("Delete", "SasProgram", FormMethod.Post, new { id = "deleteForm" }))
{
    <input type="submit" class="button" value="Delete" />
}

<input type="submit" class="button" value="Save" form="editForm"/>
<input type="submit" class="button" value="Delete" form="deleteForm" />

This allows for a nice button layout without any fancy javascript or css styling.

这允许一个漂亮的按钮布局,而无需任何花哨的 javascript 或 css 样式。

回答by AdemusPrime

The OLD way to do this but still applicable is to have one form tag and change the action with multiple submit buttons.

执行此操作但仍然适用的旧方法是使用一个表单标签并使用多个提交按钮更改操作。

<input class="btn btn-default" type="submit" value="Save" />
<input class="btn btn-default" type="submit" value="Delete" onclick="this.form.action='/SasProgram/delete/@Model.Id';" />