0

I am building a search view in asp.net MVC 2

So I have:

public ActionResult Search()
{
    ...
}


[HttpPost]
public ActionResult Search(string input, FormCollection formValues)
{
    ...
}

The problem is in the view there is a textbox and two buttons "Search" and "Clear Results".

Once entering the [HttpPost] method how do I work out which button has been clicked ? (So I can change the search & display logic) - or does this have to be a link instead?

baron
  • 11,011
  • 20
  • 54
  • 88
  • http://stackoverflow.com/questions/442704/how-do-you-handle-multiple-submit-buttons-in-asp-net-mvc-framework – Diego Nov 05 '10 at 01:01

3 Answers3

3

I've developed this quick little ActionMethodSelectorAttribute

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

    public AcceptParameterAttribute(string name)
    {
        Name = name;
    }

    public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
    {
        HttpRequestBase req = controllerContext.HttpContext.Request;
        return req.Form[Name] != null;
    }
}

You can use this on your actions like this

[HttpPost]
[AcceptParameter("submitBtnName")]
public ActionResult Search()
Phil
  • 157,677
  • 23
  • 242
  • 245
3

Reset forms on the client side.

Use for the form submit button. Use type="reset" for the reset button.

Otherwise, use javascript to wire up the reset button.

Phil Winkel
  • 161
  • 4
2

If the buttons are INPUT tags and you've assigned them "name" values, they will be POSTed back to your FormCollection. You will see the "buttonName" = "value" in your array. Just check the collection for the proper key and you'll know which was pressed.

Another way to do it is to have a hidden input within your form and when the users clicks button "A", stuff a value in the hidden input. If the user clicks button "B", stuff a different value in your input. When you get back to your server, just check which value the hidden input has.

lucifurious
  • 630
  • 5
  • 11