Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 button click event

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.

like image 327
TJK Avatar asked Aug 25 '11 16:08

TJK


3 Answers

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

like image 134
ipr101 Avatar answered Oct 06 '22 10:10

ipr101


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.

like image 34
itsmatt Avatar answered Oct 06 '22 09:10

itsmatt


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")'" >
like image 21
kavitha Reddy Avatar answered Oct 06 '22 09:10

kavitha Reddy