cmnunis
cmnunis

Reputation: 71

Creating a custom button in ASP.NET MVC (not buttons for Create, Read, Update, Delete)

I don't know if you have run into a similar situation but here's a requirement that has been given to me:-

I run an ASP.NET MVC site which manages our client company details. Due to usability concerns, we have been asked to remove some checkboxes and replace them with a generic "Apply" button on our Edit page.

The current scenario that we have on our Edit page is:

  1. Checkbox for "Enable Speed Settings for all Assets"
  2. Checkbox for "Enable Corrective Actions for all Assets"
  3. At the click of the Save button, a trigger updates the database.

What is currently required now, is one button to do both operations. This obviously needs a new NHibernate stored procedure but that's an issue for later. Therefore, what I'm interested is, can a button of this sort be achieved in MVC? If so, has anyone had any experience which would help, specifically in constructing the ActionResult methods? Thank you. :)

Upvotes: 0

Views: 2104

Answers (1)

Dmitry Reznik
Dmitry Reznik

Reputation: 6862

I'd recommend looking here for the solution:

http://weblogs.asp.net/dfindley/archive/2009/05/31/asp-net-mvc-multiple-buttons-in-the-same-form.aspx

Basically, you can send data to your action method and check there what course of action to take - save or apply. Or you can divide them into two controller actions something like this (apprehended from the article above):

[ActionName("Register")]
[AcceptVerbs(HttpVerbs.Post)]
[AcceptParameter(Name="button", Value="cancel")]
public ActionResult Register_Cancel()
{
    return RedirectToAction("Index", "Home");
}

[AcceptVerbs(HttpVerbs.Post)]
[AcceptParameter(Name="button", Value="register")]
public ActionResult Register(string userName, string email, string password, string confirmPassword)
{
   // process registration
}

Buttons

<button name="button" value="register">Register</button>
<button name="button" value="cancel">Cancel</button>

Simple filter:

public class AcceptParameterAttribute : ActionMethodSelectorAttribute
{
    public string Name { get; set; }
    public string Value { get; set; }

    public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
    {
        var req = controllerContext.RequestContext.HttpContext.Request;
        return req.Form[this.Name] == this.Value;
    }
}

Upvotes: 1

Related Questions