如何将多个参数从javascript函数传递给控制器

时间:2014-01-13 14:21:48

标签: .net asp.net-mvc jquery

我知道我们可以通过指定它们来分别发送多个参数,但是如果参数的计数是动态的,那么该怎么办。下面的代码适用于特定数量的参数。如何完成多个可以改变计数的参数的发送?

 $.ajax({
            type: "POST",
            url: 'Home/xxx',             
            data: { "FirstName": FirstName, "LastName": LastName,"InputNo3": InputNo3, "InputNo4": InputNo4, "InputNo5": InputNo5 }
        }).done(function (msg) {
            $(".popup").html(msg);
            $(".background").show();
        });

2 个答案:

答案 0 :(得分:0)

如果您有许多不同类型的参数,如string,int,object,那么您可以将其添加到object并发送。

var myComplextObject={};
myComplextObject.FirstName='';
myComplextObject.Age=27;
myComplextObject.Address={};
myComplextObject.Address.City='Chennai';

//etc
$.ajax({
        type: "POST",
        url: 'Home/xxx',             
        data: myComplextObject
    }).done(function (msg) {
        $(".popup").html(msg);
        $(".background").show();
    });

答案 1 :(得分:0)

如果参数是动态的,并且您不知道它们是什么,那么您可以使用字典作为模型。以下是Scott博客上的示例 - http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx

后端代码:

public ActionResult Blah(IDictionary<string, string> parameters) {
    if (parameters.ContainsKey("FirstName"))
    {
        var firstNameValue = parameters["FirstName"];
        // do something with it
    }
}

JavasScipt代码:

var objData = [];
objData[0].Key = "FirstName";
objData[0].Value = FirstName;
objData[1].Key = "LastName";
objData[1].Value = LastName;
objData[2].Key = "InputNo3";
objData[2].Value = InputNo3Value;
// populate other needed properties


$.ajax({
    type: "POST",
    url: 'Home/xxx',             
    data: objData
}).done(function (msg) {
    $(".popup").html(msg);
    $(".background").show();
});