使用MVC Model Binder,如何防止绑定内部复杂的对象属性?
有以下模型
public class Person
{
public int Id {get;set;}
[Required()]
public string Name {get;set;}
[Required()]
public Address Address {get;set;}
}
public class Address
{
public int Id {get;set;}
[Required()]
public string City {get;set;}
[Required()]
public string Street {get;set;}
}
我在控制器中
[HttpPost]
public ActionResult Create(Person entity)
{
if (ViewData.ModelState.IsValid)
{
///Some code
return this.RedirectToAction("Browse");
}
else
{
return View("Edit", ViewModel);
}
}
:问题是绑定器甚至尝试验证内部地址类,但我关心的是 AddressID 但 ModelBinder 甚至坚持验证 City 和 Street 属性。
我如何简单地重写原始 ModelBinder 只是为了验证内部对象的 ID(在我的情况下是 AddressID)?
有没有简单的方法?
i have the following model
public class Person
{
public int Id {get;set;}
[Required()]
public string Name {get;set;}
[Required()]
public Address Address {get;set;}
}
public class Address
{
public int Id {get;set;}
[Required()]
public string City {get;set;}
[Required()]
public string Street {get;set;}
}
in the controller:
[HttpPost]
public ActionResult Create(Person entity)
{
if (ViewData.ModelState.IsValid)
{
///Some code
return this.RedirectToAction("Browse");
}
else
{
return View("Edit", ViewModel);
}
}
the problem is that the binder try to validate even the inner address class, but all i care for, is the AddressID
but the ModelBinder insist to validate even the City and Street properties.
how can i simply override the original ModelBinder just to validate the ID of the inner object (which is in my situation is AddressID)??
is there a simple way ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来您的实体和模型有两个不同的要求。如果是这样的话,那么它们应该是两个不同的类。编写一个单独的 Person 和地址类供 MVC 绑定,并且不需要城市或街道。
另一种可能但不太优雅的解决方案是不依赖 MVC 进行模型绑定。如果您只有少数可以接受的值,但如果您有很多,那么我会使用我的第一个建议。
It sounds like your entity and your model have two different requirements. If that is the case, then they should be two different classes. Write a separate Person and address class for MVC to bind to and don't have city or street be required.
Another possible, but less elegant solution, is to not rely on MVC doing the model binding. If you only have a handful of values that may be acceptable, but if you have a lot, then I would use my first suggestion.