Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to best implement Save | Save and Close | Cancel form actions in ASP.NET MVC 3 RC

I'm wondering how you might go about implementing multiple form actions when submitting a form in asp.net mvc 3 RC.

If I'm editing a user, for example I would like to have an action bar with the following buttons;

"Save" | "Save and Close" | "Cancel"

Save - Submits the form and saves, returning you to the edit screen. Could be easily implemented as a standard input/submit button. Nothing special here.

Controller code for this might look like

public ActionResult Edit(UserViewModel model)
{
  ...
  return RedirectToAction("Edit", model.Id");
}

Cancel - Just returns you to previous screen. I was thinking about using an anchor tag for this.

<a href="@Request.UrlReferrer" class="button">Cancel</a>

But I'm stumped on how to implement "Save and Close" when you need to submit the same form data. I was wondering about having a nullable close param maybe?

public ActionResult Edit(UserViewModel model, bool? close)
{
  ...
  return  close.GetValueOrDefault(false) ? RedirectToAction("Index", model.Id" : RedirectToAction("Edit", model.Id");
}

But how do I submit this extra param along with the form in this case?

If possible, I'd like to have a single form action for handling the submit as in the above mockup.

I'm also interested if anyone else has come up with a nice user interaction model around this idea.

Solution

I ended up using Omar's suggestion below but instead of passing in a string I took in an enum so I don't have to do string checks in all my controllers.

public ActionResult Edit(UserViewModel model, FormAction actionType)
{
  // pre-check
  if (actionType == FormAction.Cancel)
     // just return user to previous view and don't save.

  // Save code

  if (actionType == FormAction.Save)
     return ...
  else if (actionType == FormAction.SaveAndClose)
     ....
}

Because I wanted a friendlier "Save and Close" text on the <input> button but wanted to use an enum I implemented a custom ModelBinder for FormAction that did the parsing.

I didn't use a <button> tag because the theming was already in place for <input> tags.

like image 724
Joshua Hayes Avatar asked Nov 24 '10 06:11

Joshua Hayes


People also ask

Which model method are used to save the MVC?

Right-click on Model then select New Item > Data template (ADO.NET Entity Data Model). Name your model “MyModel” then select Generate From Database then enter your configuration then select your table.

What is ActionResult () in MVC?

An action result is what a controller action returns in response to a browser request. The ASP.NET MVC framework supports several types of action results including: ViewResult - Represents HTML and markup. EmptyResult - Represents no result.

How many types of action methods are there in MVC?

Figure 2: Types of Action Result There are two methods in Action Result. One is ActionResult() and another one is ExecuteResult().

Which is the default action method invoked in ASP NET MVC?

By default, the Index() method is a default action method for any controller, as per configured default root, as shown below. routes. MapRoute( name: "Default", url: "{controller}/{action}/{id}/{name}", defaults: new { controller = "Home", action = "Index", id = UrlParameter. Optional });


2 Answers

You can have multiple submit buttons in a form with the same name attribute but different value attributes. Which ever button is clicked, the associated value will be posted to the server.

You can use a simple link for Cancel but I'll include it as a button anyway.

<input type="submit" name="actionType" value="Save" />
<input type="submit" name="actionType" value="Save and Close" />
<input type="submit" name="actionType" value="Cancel" />

And in your action, test for the values.

public ActionResult Edit(string actionType)
{
    if(actionType == "Save")
    {
        // Save action
    }
    else if (actionType == "Save and Close")
    {
        // Save and quit action
    }
    else
    {
        // Cancel action
    }
}

If you don't like having the long text in the value attribute, you can use standard HTML <button> tag which lets you define a separate value and separate text.

like image 195
Omar Avatar answered Oct 21 '22 00:10

Omar


The suggestion by @Omar is great. Here is how I made this a little more generic in the case where I wanted a confirmation when the user is prompted to delete an object. Note! in the HttpPost I'm pulling the object again rather than using the item passed to the method. You can reduce a DB call by the having the view contain all the properties so "Item" is populated.

Here's the View Model

public class DeleteViewModel<T> {
    public string ActionType { get; set; }
    public T Item { get; set; }
}

Controller

    public ActionResult Delete(int id) {
        DeleteViewModel<Category> model = new DeleteViewModel<Category>() {
            Item = categoryRepository.Categories.FirstOrDefault(x => x.CategoryID == id)
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Delete(DeleteViewModel<Category> model) {
        if (model.ActionType == "Cancel")
            return RedirectToAction("Index");
        else if (model.ActionType == "Delete") {
            var cat = categoryRepository.Categories.FirstOrDefault(x => x.CategoryID == model.Item.CategoryID);
            categoryRepository.Delete(cat);
            return RedirectToAction("Index");
        }        
        //Unknown Action
        return RedirectToAction("Index");
    }

View

    <div class="actions">
        <div class="actions-left"><input type="submit" value="Cancel" name="ActionType"/></div>
        <div class="actions-right"><input type="submit" value="Delete" name="ActionType" /></div>
    </div>   
like image 22
anAgent Avatar answered Oct 21 '22 00:10

anAgent