Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

like image 985
Mike Perrenoud Avatar asked Jul 15 '13 19:07

Mike Perrenoud


People also ask

How will you implement insert update delete functionality in single view of ASP NET MVC?

Step 1 : Create the table in your database with the following script. Step 2 : Now create a new ASP.Net MVC3 Web application with an empty template. This will create one predefined structure with Controllers, Modes and Views folders. All these folders are empty; now we have to add the content to these folders.


2 Answers

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.

like image 110
nrodic Avatar answered Oct 17 '22 12:10

nrodic


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.
like image 15
Kristof Claes Avatar answered Oct 17 '22 12:10

Kristof Claes