javascript – 当对集合使用getter时,ASP.NET MVC3模型绑定器数据无效
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 当对集合使用getter时,ASP.NET MVC3模型绑定器数据无效,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1930字,纯文字阅读大概需要3分钟。
内容图文
有了这个Contact模型
public class Contact
{
public string Name { get; set; }
public ICollection<Phone> Phones { get; set; }
public Phone PrimaryPhone
{
get { return Phones.FirstOrDefault(x => x.Primary) ?? new Phone(); }
}
}
public class Phone
{
public bool Primary { get; set; }
public string PhoneNumber { get; set; }
public string Type { get; set; }
}
而这个控制器
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Contact contact)
{
return View();
}
}
当我使用jQuery POST到HomeController索引时
(function ($) {
var myData = {
Name: 'Wesley Crusher',
Phones: [
{ Primary: false, PhoneNumber: '111-111-1111', Type: 'Business' },
{ Primary: true, PhoneNumber: '222-222-2222', Type: 'Personal' },
{ Primary: false, PhoneNumber: '333-333-3333', Type: 'Business' }
],
PrimaryPhone: { Primary: true, PhoneNumber: '111-111-1111', Type: 'Business' }
};
$.ajax({
url: '@Url.Action("Index", "Home")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(myData)
});
})(jQuery)
模型绑定器不正确会构建ICollection电话.数据是:
> [0] Primary = false,PhoneNumber =“111-111-1111”,Type =“Business”MVC3ModelBinderJsonTesting.Models.Phone
> [1] Primary = true,PhoneNumber =“111-111-1111”,Type =“Business”MVC3ModelBinderJsonTesting.Models.Phone
> [2] Primary = false,PhoneNumber =“333-333-3333”,Type =“Business”MVC3ModelBinderJsonTesting.Models.Phone
重复PhoneNumber“111-111-1111”,类型为“Business”而不是“Personal”.出于某种原因这是预期的行为还是这个错误?
如果您愿意,我可以发布一个示例项目,请告诉我.
解决方法:
我认为这是因为它不是原始的.它是一个复杂的对象,因此模型绑定器会尝试设置其属性.
模型绑定更适合绑定“输入模型”,后者表示来自表单的输入.在输入模型上使用业务逻辑计算属性可能不是您所看到的最佳方法.
你可能有一个扩展方法(遗憾的是不支持扩展属性)而不是输入模型的属性.甚至是一个合适的方法.拥有它成为一个属性使模型绑定器认为它是公平的游戏.
如果它是一个只获取原始类型,它将不会尝试设置它.
内容总结
以上是互联网集市为您收集整理的javascript – 当对集合使用getter时,ASP.NET MVC3模型绑定器数据无效全部内容,希望文章能够帮你解决javascript – 当对集合使用getter时,ASP.NET MVC3模型绑定器数据无效所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。