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.
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 -
http://weblogs.asp.net/dfindley/archive/2009/05/31/asp-net-mvc-multiple-buttons-in-the-same-form.aspx
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.
<input type="button" name="button" id="btnadd" value="Add" onclick="location.href='@Url.Action("ActionResultName", "ControllerName")'" >
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With