以下代码成功地使用了 ajax,尽管我不确定 MVC 中的服务器端 ActionResult 如何理解正在发送的对象。有任何想法吗?需要从 jquery 发布的对象是一个具有多个属性的对象。 谢谢
var url = 'abc';
//val: { several properties, forename, surname, postcode
jr.ajax.loadJson(url, val,
true,
function(xhr, textStatus, errorThrown) {
},
true, 'post', val);
});
// controller
public ActionResult Show()
{
var list = Request.Form[0]; // can see the values in here
}
// I want the posted value to be this object
public class Test
{
public string forename { get; set; }
public string surname { get; set; }
public string postcode { get; set; }
}
最佳答案
您需要将对象发布到需要具有类似属性的对象参数的操作。我不太确定 loadJSON
的作用(我假设它是您正在使用的插件?),但是,在发布数据时,您可以使用标准 $.ajax
方法,或者$.post
用于更简单的 API,例如
服务器端
public class MyModel
{
public string Property1 { get; set; }
public string Property2 { get; set; }
...
}
[AjaxOnly]
public ActionResult Show(MyModel model)
{
// use model
}
客户端
var obj = { Property1: 'value1', Property2: 'value2' };
$.post(url, obj, function(response) {
alert('post successful!');
});
当数据到达服务器时,MVC 尝试使用名称/值对方法将客户端对象绑定(bind)到预期的服务器端类型。换句话说,只要您从客户端传递的对象具有完全相同相同名称的属性以及该特定属性类型的有效值,它就会成功映射。
关于c# - 如何发布 ajax 调用和 C# 来识别对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17213024/