bind attribute include and exclude property with complex type nested objects

前端 未结 2 660
再見小時候
再見小時候 2020-12-14 23:44

Ok, this is weird. I cannot use BindAttribute\'s Include and Exclude properties with complex type nested objects on ASP.NET MVC.

2条回答
  •  太阳男子
    2020-12-15 00:09

    Yes, you can make it work like that:

    [Bind(Include = "EnquiryId")]
    public class Enquiry 
    {
        public int EnquiryId { get; set; }
        public string Latitude { get; set; }
    }
    

    and your action:

    [ActionName("Foo"), HttpPost]
    public ActionResult Foo_post(FooViewModel foo) 
    {
        return View(foo);
    }
    

    This will include only the EnquiryId in the binding and leave the Latitude null.

    This being said, using the Bind attribute is not something that I would recommend you. My recommendation is to use view models. Inside those view models you include only the properties that make sense for this particular view.

    So simply readapt your view models:

    public class FooViewModel 
    {
        public EnquiryViewModel Enquiry { get; set; }
    }
    
    public class EnquiryViewModel 
    {
        public int EnquiryId { get; set; }
    }
    

    There you go. No longer need to worry about binding.

提交回复
热议问题