gpt4 book ai didi

javascript - MVC Controller 属性无法识别参数的集合

转载 作者:行者123 更新时间:2023-11-28 16:05:29 25 4
gpt4 key购买 nike

我正在调用 MVC Controller 方法并向其传递一个 Entity 对象。除其他属性外,Entity 还具有 Contacts 属性。通过这种方法, Controller 获取实体以及实体中正确的联系人数量,但所有联系人的属性均为空。

这是原始方法:

$.post('/Home/Save', $.param(entity), SaveComplete);

使用强类型 Controller :

public ActionResult Save(Entity entity)

这会导致每个 Entity.Contact 具有 null 属性:

enter image description here

Fiddler 显示联系人已传递到服务器。

为了让 Controller 识别实体的 Contacts 属性,我必须这样做:

JavaScript:

$.post('/Home/Save', { entityAsJson: JSON.stringify(entity) }, SaveComplete);

Controller 方法:

public ActionResult Save(string entityAsJson)
{
try
{
Entity entity = JsonConvert.DeserializeObject<Entity>(entityAsJson);
// more code here
}
}

这很不幸,因为现在我的 Controller 采用字符串而不是强类型实体。有没有办法让第一个选项起作用,或者我需要对 JSON 进行字符串化吗?

最佳答案

为了在 Controller 操作中使用强类型参数并使用正确绑定(bind)的 ajax 发送数据(包括集合属性),您需要执行以下操作:

  • 使用 $.ajax 而不是 $.post 因为 $.post 不允许配置 contentType 选项
  • 您需要发送 JSON。所以你需要JSON.stringfy你的数据
  • contentType 设置为 “application/json”,因为这会告诉 ASP.NET MVC 使用正确的 JSON 模型绑定(bind)器

因此以下代码应该适用于您的原始 Controller 操作:

$.ajax({ 
url: '/Home/Save',
type: 'POST',
data: JSON.stringify(entity),
contentType: "application/json",
success: SaveComplete
});

关于javascript - MVC Controller 属性无法识别参数的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15179007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com