简体   繁体   English

来自带有参数的jquery的mvc调用控制器

[英]mvc call controller from jquery with parameter

I want to call MVC controller method from Jquery. 我想从Jquery调用MVC控制器方法。 Below is my code but it is not working 下面是我的代码,但它不起作用

Controller: 控制器:

    public ActionResult singleValue(string valuetoset)
    {
        //Code
    }

JQuery: JQuery的:

$('#User').live('change', function (e) {
    var userValue = e.target.options[e.target.selectedIndex].value;

 $.ajax({
        url: "/Home/singleValue",
        type: 'GET',
         data: { valuetoset: userGuideValue },
        success: function (result) {
            alert(result);
        },
        error: function () {
            alert("error");
        }
    });
});

I need to pass valuetoset argument, but it always going as null 我需要传递valuetoset参数,但它始终为null

您需要更改url ajax方法应如下所示:

url:'@Url.Action("Home", "singleValue")',

Your data parameter needs to be in JSON format. 您的data参数必须为JSON格式。 There are a number of ways to do so, here's one: 有很多方法可以做到,这是一种:

var myData = {};
myData["valuetoset"] = userValue;

Here, valuetoset corresponds to your controller action parameter. 在这里, valuetoset对应于您的控制器操作参数。 Then, your data declaration should be as follows: 然后,您的data声明应如下所示:

data: myData

Or, you could just include userValue in your URL if your routes are set up correctly since this is a GET action: 或者,如果路由设置正确,则只需在URL中包含userValue ,因为这是GET操作:

url: host + "/Home/singleValue/" + userValue

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM