MVC3 Button Press Event

I should have 3 buttons in my opinion (Add, Save, Cancel). If I click on these buttons, they should click on the appropriate methods in the controller. How to reach button click event in MVC3? Can someone provide me an example? Suggest me if it is better.

+8
asp.net-mvc-3 buttonclick
source share
3 answers

There is no server-side button click event in MVC 3, you will need to decide which button was clicked based on the values ​​of the forms you submitted back. Take a look at this blog post for further information -

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

+9
source share

I am really new to ASP.NET MVC, but the way I solved it was that I had several buttons in my form and gave each of them a class, and then set the data parameters for them, in this For example, I have two properties from some element Val1 and Val2 for the first button, and two for the second - Val1 and Val3:

<input type="button" value="Button 1" class='button1' data-val1="@item.Val1" data-val2="@item.Val2"/> <input type="button" value="Button 2" class='button2' data-val1="@item.Val1" data-val2="@item.Val3"/> 

and then I used some jquery to handle click events and indicated which action to trigger:

 <script type="text/javascript"> $(function () { $('.button1').click(function () { var Val1 = $(this).data('val1'); var Val2 = $(this).data('val2'); $.ajax({ type: "POST", data: "val1=" + Val1 + "&val2=" + Val2, url: '@Url.Action("MyAction", "MyController")', dataTyp: "html", success: function (result) { // whatever I did here on success } }); }); }); // rinse and repeat for the other button, changing the parameters and the action called. </script> 

It seemed to work very well for my needs.

+7
source share

The button click event below calls the relevant actionResult method in the controller

  <input type="button" name="button" id="btnadd" value="Add" onclick="location.href='@Url.Action("ActionResultName", "ControllerName")'" > 
+1
source share

All Articles