C# 通过Ajax发送数组并绑定到列表<;字符串>;关于mvc4
AJAX:C# 通过Ajax发送数组并绑定到列表<;字符串>;关于mvc4,c#,ajax,asp.net-mvc,asp.net-mvc-4,asp.net-ajax,C#,Ajax,Asp.net Mvc,Asp.net Mvc 4,Asp.net Ajax,AJAX: function systemsChanged(elem) { var items = []; for (i = 0; i < elem.length; i++) if (elem[i].selected) { items.push(elem[i].value); } var post = { ids: items }; $.ajax({ type: "POST",
function systemsChanged(elem)
{
var items = [];
for (i = 0; i < elem.length; i++)
if (elem[i].selected) {
items.push(elem[i].value);
}
var post = { ids: items };
$.ajax({
type: "POST",
traditional: true,
url: "@Url.Action("LoadApplicationConfigs", "Application")",
content: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(post),
success: function (d) {
alert(d.message);
},
error: function (xhr, textStatus, errorThrown) {
alert("não rolo");
}
});
}
[HttpPost]
public JsonResult LoadApplicationConfigs(IList<string> ids)
{
object data = new
{
message = "aha!"
};
return new JsonResult() { Data = data };
}
功能系统更改(元素)
{
var项目=[];
对于(i=0;i
C#MVC4:
function systemsChanged(elem)
{
var items = [];
for (i = 0; i < elem.length; i++)
if (elem[i].selected) {
items.push(elem[i].value);
}
var post = { ids: items };
$.ajax({
type: "POST",
traditional: true,
url: "@Url.Action("LoadApplicationConfigs", "Application")",
content: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(post),
success: function (d) {
alert(d.message);
},
error: function (xhr, textStatus, errorThrown) {
alert("não rolo");
}
});
}
[HttpPost]
public JsonResult LoadApplicationConfigs(IList<string> ids)
{
object data = new
{
message = "aha!"
};
return new JsonResult() { Data = data };
}
[HttpPost]
公共JsonResult加载应用程序配置(IList ID)
{
对象数据=新建
{
message=“啊哈!”
};
返回新的JsonResult(){Data=Data};
}
它进入post方法,但
ids
设置为null
。我还尝试将ids
更改为string[]
,但没有成功。回到ajax很好:它显示了“aha!”警报。我似乎无法为mvc活页夹提供准确的格式。有什么想法吗?更新ajax调用:
$.ajax({
type: "POST",
traditional: true,
url: "@Url.Action("LoadApplicationConfigs", "Application")",
content: "application/json; charset=utf-8",
dataType: "json",
data: post,
success: function(d) {
alert(d.message);
},
error: function(xhr, textStatus, errorThrown) {
alert("não rolo");
}
});
无论是否使用
传统的
选项,这都可以工作。尝试将其简化为JSON。stringify(items)JSON。stringify(items)不起作用正如Matt所说,该方法只需要一个字符串数组,为了让它接受您发送的内容,您必须创建一个具有名为“ids”属性的包装类/结构,这似乎毫无意义。@Simon先生,我不确定这是否会产生影响,但我会让你的参数IEnumerable
@BenRobinsonIEnumerable
无效。它有效,我会将其标记为答案,但首先解释post.id
部分。为什么post
有一个名为ids
的属性?如果我更改了方法中的参数,是否必须更改它?为数据设置的对象必须具有与操作方法中的参数名称完全匹配的字段名称。由于ids
预计为IList
,因此对整个post
对象的ids
设置将不起作用,因此模型绑定器将因此阻塞。在原始代码中,您的ID被设置在post
对象上名为ids
的字段上,这是您要发送到服务器的数据。在进一步测试中,您也可以将data
设置为与post
对象相等,因为字段名称与操作方法参数名称匹配。哎哟:)我更新了答案来演示。该死!我以前怎么没试过。我决定使用JSON.stringify方法。那好多了,谢谢你!