使用MVC Model Binder,如何防止绑定内部复杂的对象属性?

发布于 2024-10-08 02:12:50 字数 897 浏览 0 评论 0原文

有以下模型

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

被你宠の有点坏 2024-10-15 02:12:50

听起来您的实体和模型有两个不同的要求。如果是这样的话,那么它们应该是两个不同的类。编写一个单独的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文