简体   繁体   English

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

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

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 Delete button on the same view as the Edit . 我想在“ Edit的同一视图上显示“ Delete按钮。 However, it's not letting me have nested forms. 但是,它不会让我有嵌套的表单。 What is the appropriate way to handle this situation? 处理这种情况的适当方法是什么?

I tried leveraging this answer, How to handle nested forms in ASP.NET MVC , but it's a broken link now. 我尝试利用这个答案, 如何处理ASP.NET MVC中的嵌套表单 ,但现在它已经是一个破碎的链接。

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. 请注意,按钮是默认类型 - 提交。

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 没有GET请求
  • The delete button below the edit button, which makes more sense when you're on a view that allows you to edit something. 编辑按钮下方的删除按钮,当您在允许编辑内容的视图上时更有意义。

First of all. 首先。 Every modification request should be use the post method. 每个修改请求都应该使用post方法。
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 . 我在wiki中进行了一些研发并构建了多提交按钮处理程序的基础知识在ASP.NET MVC中使用多个提交按钮的干净解决方案
I think it could solve your problem. 我认为它可以解决你的问题。

First, you cannot nest <form> element. 首先,您不能嵌套<form>元素。 The specification doesn't allow it. 规范不允许。 Since you are using the MVC pattern I have two options that came to my mind: 由于您使用的是MVC模式,因此我想到了两个选项:

  1. You can retain the save button as the submit button of the form, and make the delete button a HTML link. 您可以将保存按钮保留为表单的提交按钮,并将删除按钮设置为HTML链接。 Then the delete button will target to a different route, it could be something like: GET /program/delete/{id} . 然后删除按钮将定位到不同的路线,它可能是: 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 action attribute of the form. 您可以在同一表单中使用两个按钮,然后在单击其中一个按钮后使用JavaScript,您将更改表单的操作属性。

Update 更新

There is a third option, that is more clean: using two submit buttons with same name attribute and different values . 还有第三个选项,它更干净:使用两个具有相同名称属性和不同值的提交按钮。

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

You can also use html 5 feature to target a form from an input button. 您还可以使用html 5功能从输入按钮定位表单。 Below I have created both a delete and save form and have the submit buttons outside of the forms but targeting them via the form attribute. 下面我创建了一个删除和保存表单,并在表单外部提交了按钮,但是通过form属性定位它们。

I think most browsers support this except IE. 我认为大多数浏览器都支持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风格。

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';" />

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. 这将有效,但为了获得更好的用户体验,最好在索引/列表视图中使用“删除”按钮,并在执行ajax发布之前使用JQuery UI对话框进行确认。 This will skip having to load the Edit page if/when you want to delete multiple items one after the other. 如果/当您想要一个接一个地删除多个项目时,这将跳过必须加载编辑页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM