I should have 3 buttons in my view(Add, Save, Cancel). If I click these buttons they should hit relevant methods in the controller. How do i achieve button click event in MVC3? Can anyone provide me with an example? Suggest me if any better way.
Asked
Active
Viewed 4.1k times
3 Answers
9
There's no server side button click event in MVC 3, you'll need to work out which button was clicked based on the form values you get posted back. Have a look at this blog post for further info -

ipr101
- 24,096
- 8
- 59
- 61
7
I'm really new to ASP.NET MVC but a way that I solved this was that I had a couple of buttons on my form and gave each of them a class, and then specified the data parameters for them, in this example I've got two properties from some item 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 the click events and specified which action to call:
<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>
This seemed to work pretty well for my needs.

itsmatt
- 31,265
- 10
- 100
- 164
1
The below button click event hits the relevent actionResult method in the controller
<input type="button" name="button" id="btnadd" value="Add" onclick="location.href='@Url.Action("ActionResultName", "ControllerName")'" >

kavitha Reddy
- 3,303
- 24
- 14
-
Would be great if you included an explanation together with the code – Emil Vikström Sep 04 '14 at 07:03
-
Thank you 'Emil Vikström' for your kind advice. – kavitha Reddy Sep 04 '14 at 07:10