UpdateModel prefix - ASP.NET MVC

后端 未结 4 1225
悲哀的现实
悲哀的现实 2020-12-29 12:23

I\'m having trouble with TryUpdateModel(). My form fields are named with a prefix but I am using - as my separator and not the default dot.

<         


        
相关标签:
4条回答
  • 2020-12-29 12:50

    Another thing to note is that the prefix is to help reflection find the proper field(s) to update. For instance if I have a custom class for my ViewData such as:

    public class Customer
    {
        public string FirstName {get; set;}
        public string LastName {get; set;}
    }
    
    public class MyCustomViewData
    {
        public Customer Customer {get; set;}
        public Address Address {get; set;}
        public string Comment {get; set;}
    }
    

    and I have a textbox on my page

    <%= Html.TextBox("FirstName", ViewData.Model.Customer.FirstName) %>
    

    or

    <%= Html.TextBox("Customer.FirstName", ViewData.Model.Customer.FirstName) %>
    

    here is what works

    public ActionResult Save (Formcollection form)
    {
        MyCustomViewData model = GetModel(); // get our model data
    
        TryUpdateModel(model, form); // works for name="Customer.FirstName" only
        TryUpdateModel(model.Customer, form) // works for name="FirstName" only
        TryUpdateModel(model.Customer, "Customer", form); // works for name="Customer.FirstName" only
        TryUpdateModel(model, "Customer", form) // do not work
    
        ..snip..
    }
    
    0 讨论(0)
  • 2020-12-29 12:57

    that was bad decision to use period. Underscore would have been better.

    This means you have to separately define all your ids.

    ie. Textbox now has Html.TextBox("test.test", new{@id="test")

    0 讨论(0)
  • 2020-12-29 13:15

    Not unless you implement your own ModelBinder. If you look at the source code for the DefaultModelBinder on www.codeplex.com/aspnet, you'll see that when you specify a prefix it constructs the name by concatenating the prefix, a period, and the name of the property. Unfortunately, the method on DefaultModelBinder that does this is private static and thus cannot be overridden in a derived class.

    0 讨论(0)
  • 2020-12-29 13:16

    There is a reason not to use . as ID/Name in HTML bcs it is not standard. For example, the will break if there is a dot in target.

    0 讨论(0)
提交回复
热议问题