Skip to main content
 首页 » 编程设计

c#之通过 $ 动态发送数据。 Ajax 方法

2024年01月28日36shangdawei

我在 MVC 网站项目中使用 jquery。

我有一个名为“testController”的简单 C# Controller :

public class testController 
{ 
    public string test(string id) 
    { 
        return id; 
    } 
} 

..以及使用它的 javascript 函数:

function myfunct(sData) { 
    $.ajax({ 
        type: "POST", 
        async: false, 
        datatype: "json", 
        url: '/test/test', 
        data: '{' + sData + '}', //Not Working if I set sData = "id:'Hello'" 
                                 //Work if I write data = { id:'hello'}, 
        success: function (json) { 
            alert(json); //Need to return 'Hello' 
        } 
    }); 
} 

..有办法动态分配“数据”参数吗?

请您参考如下方法:

只要您传递的对象中的属性与操作接受的类型的属性相匹配,您就可以根据需要创建对象。试试这个:

var sData = { id: 1234 }; // note 'id' matches the property in the signature of the action method 
 
// in the $.ajax() call properties... 
data: sData 

这也适用于类。例如,如果您的 Controller 中有此类和操作:

public class Foo { 
    public int Id { get; set; } 
    public string Name { get; set; } 
} 
 
// in controller: 
public ActionResult Bar(Foo myFoo) { 
    // do stuff with Foo 
} 

然后您可以通过 $.ajax 以这种形式传递一个 javascript 对象:

var data = { Id: 1234, Name: 'Foo bar' }; 

请注意,属性会映射到方法签名中类的属性。