我最近一直在努力使用新的 ASP.NET 5
系统和 Microsoft 的 ASP.NET MVC 6
,但我发现了一些非常关键的问题阻碍我前进;最值得注意的是,我似乎无法再通过 Controller 方法传递多个 JSON
参数。
例如,我有以下 Controller 方法;
[HttpPost]
[Route("edit/profile")]
public void Attribute([FromBody]Models.Profile model, bool editing) {
// ...
// model always comes in null
// editing always comes in default (false)
}
我正在尝试使用 $.ajax
将数据传递到此 Controller 。
$.ajax({
url: '/edit/profile',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({ model: _this.model, editing: true })
});
但无论我做什么, Controller 上的参数始终为 null
。我尝试了各种方法,如果我忽略 ({ model : _this.model ... })
部分并仅传递一个参数,它就会按预期显示 data: JSON .stringify(_this.model)
模型看起来像这样; (显然不是最终模型,只是我解决这个问题时的一个虚拟模型)
_this.model = {
Id: null,
Name: null
Text: null
};
并且它对应于这个C#
类;
namespace Models {
public class Profile {
public string Id { get; set; }
public string Name { get; set; }
public string Text { get; set; }
}
}
我就是无法弄清楚我的一生。这在 MVC 5
上运行良好,但自从升级以来它就完全失效了。
我也在使用jQuery 2.1.4
最佳答案
我也有类似的问题。我已经通过使用单独的数据类解决了这个问题。
[HttpPost]
[Route("edit/profile")]
public void Attribute([FromBody] ProfileData data)
{
var model = data.Model;
var editing = data.Editing;
}
public class ProfileData
{
public Models.Profile Model { get; set; }
public bool Editing { get; set; }
}
$.ajax({
url: '/edit/profile',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: { data: { Model: _this.model, Editing: true } }
});
关于jquery - MVC 6 - 无法再将多个 JSON 参数传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32866350/