Pages

Thursday, April 7, 2011

Handling multiple button clicks in same View using ASP.NET MVC2,0

This post explains, how to handle multiple button click events in the same page using ASP.NET MVC.

One basic thing to remember is, when ever you have any post methods to be performed, you need to have all your controls within the begin form.

The following methods explains to implement multiple buttons

Method 1:
        Each button should be defined within its own begin form. So on click, post method would be called only for the form which caused the post action. Thus in the post ActionResult method - the form collection would contain only the respective button which we clicked.
And in action result method, we coud have a if condition with the button name, and inside the if we could have the respective click functionality to be performed

Drawback: In post method we can retrieve only those controls within the begin form where the button is defined. Thus this method will not be appt when we want to access the controls by different buttons.

Method 2:
       In all the input tags, specify the same name field and different value field. By doing this, in the post method, with what ever the button is clicked, we would have the same name for all the buttons. Thus this button could be retrieved by using form collection or by having button name as one of the parameter in the post method.
Once the method is posted, in the post action result, can have multiple if conditions with input tag's value check, and for the corresponding value - can call the button click funtionality to be performed.

Example:
in aspx page:


input type="submit" name ="ButtonClick" value="Button1" title="Click Button1"
input type="submit" name ="ButtonClick" value="Button2" title="Click Button2"
input type="submit" name ="ButtonClick" value="Button3" title="Click Button3"


public ActionResult MultipleButtonsInSamePage(string ButtonClick)
{
       if (ButtonClick.Equals("Button1"))
      {
           //Perform function for button1 click
      }
      else if (ButtonClick.Equals("Button2"))
     {
          //Perform function for button2 click
     }
     else if (ButtonClick.Equals("Button3"))
     {
         //Perform function for button2 click
     }
     return View();
}

No comments:

Post a Comment