How do you exclude properties from binding when calling UpdateModel()?

后端 未结 4 796
伪装坚强ぢ
伪装坚强ぢ 2020-12-20 11:46

I have a view model sent to the edit action of my controller. The ViewModel contains references to EntityObjects. (yea i\'m fine with it and don\'t need to want to duplicate

相关标签:
4条回答
  • 2020-12-20 11:51

    A very simple solution that I figured out.

     try
    {
       UpdateModel<SimplifiedCompanyViewModel>(model, String.Empty, null, excludeProperties);
       ModelState.Remove("Entity.RetainedEarningsAccount.AccountNo");
       ModelState.Remove("Property.DiscountEarnedAccount.ExpenseCodeValue");
       ModelState.Remove("Entity.EntityAlternate.EntityID");
       ModelState.Remove("Property.BankAccount.BankAccountID");
       ModelState.Remove("Entity.PLSummaryAccount.AccountNo");
       ModelState.Remove("Property.RefundBank.BankAccountID");
       ModelState.Remove("ompany.Transmitter.TCC");
    
        if (ModelState.IsValid)
        {
           //db.SaveChanges();
        }
           return RedirectToAction("Index");
    }
    catch
    {
        return View(model);
    }
    
    0 讨论(0)
  • 2020-12-20 11:52

    Another option here is simply don't include this attribute in your view and it won't be bound. Yes - you are still open to model injection then if someone creates it on the page but it is another alternative. The default templates in MVC will create your EditorFor, etc as separate items so you can just remove them. This prevents you from using a single line view editor with EditorForModel, but the templates don't generate it that way for you anyways.

    EDIT (adding above comment)

    DRY generally applies to logic, not to view models. One view = one view model. Use automapper to easily map between them. Jimmy Bogard has a great attribute for this that makes it almost automatic - ie you create the view model, load up your Customer entity for example, and return it in the action method. The AutpMap attribute will then convert it to a ViewModel. See lostechies.com/jimmybogard/2009/06/30/how-we-do-mvc-view-models

    0 讨论(0)
  • 2020-12-20 12:11

    Use the Exclude property of the Bind attribute:

    [Bind(Exclude="Id,SomeOtherProperty")]
    public class SimplifiedCompanyViewModel
    {
        public int Id { get; set; }
    
        // ...
    }
    

    This is part of the System.Web.Mvc namespace. It takes a comma-separated list of property names to exclude when binding.

    Also you should consider using TryUpdateModel instead of UpdateModel. You can also just have the default model binder figure it out by passing it as an argument to the constructor:

    public ActionResult Create([Bind(Exclude="Id")]SimplifiedCompanyViewModel model)
    {
        // ...
    }
    
    0 讨论(0)
  • 2020-12-20 12:11

    Try the Exclude attribute.
    I admit that I haven't ever used it.

    [Exclude]
    public Entity Name {get; set;}
    
    0 讨论(0)
提交回复
热议问题