MVC button click to action [duplicate]

懵懂的女人 提交于 2019-11-30 15:41:22

问题


Possible Duplicate:
Mvc Html.ActionButton

With ASP.NET MVC 3 I know how to create a link to an action method very easily but what I'd like to know is how do you make a button (when clicked) call a particular action method?


回答1:


Sachin,

If you're using jquery (which you don't mention but I'll show as it's fairly standard with mvc), you'd do the following:

$('#buttonId').click(function(){
   document.location = '@Url.Action("MyAction","MyController")';
});

of course, you'd probably want to use ajax, but this is a basic example.




回答2:


You could use an html <form>:

@using (Html.BeginForm("SomeAction", "SomeController", FormMethod.Get))
{
    <input type="submit" value="Click me" />
}



回答3:


How do you do it? The same way you would if not using MVC.

<INPUT TYPE="BUTTON" VALUE="Home Page" ONCLICK="window.location.href='/Controller/Action'"> 



回答4:


As well as Darin's answer about using a form GET method, you can also call javascript functions that will then in turn call an action.

You can intercept the button click event when clicked and run your own code. That code can call an action asynchronously using Ajax or just simply navigate to an action method

Here's sample javascript that intercepts the button click event

$(document).ready(function () {

    myButton.onclick = function (event) {
        // in here you can call an ajax method or just navigate to an action 
        return false;
    }

    // or using jQuery
    $('#myButton').click(function (e) {
        // do whatever here
        e.preventDefault;
    });
});

Or you can intercept a button that has an href attribute

$(function () {
     $("#myButton").click(function () {
         var href = $(this).attr("href");
         var route = href + "?paramName=" + $('#SomeValue').val();
         $(this).attr("href", route);
     });
});

This adds parameter information that you may have stored in another input on the page and appends it to the Url and then navigates to the action



来源:https://stackoverflow.com/questions/10753779/mvc-button-click-to-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!