Custom ViewModel with MVC 2 Strongly Typed HTML Helpers return null object on Create?

后端 未结 3 1724
清酒与你
清酒与你 2021-01-06 10:52

I am having a trouble while trying to create an entity with a custom view modeled create form. Below is my custom view model for Category Creation form.

publ         


        
相关标签:
3条回答
  • 2021-01-06 11:38

    You could use editor templates. Put your ascx control in ~/Views/Shared/EditorTemplates/SomeControl.ascx. Then inside your main View (aspx page) include the template like so (assuming your view is strongly typed to CategoryFormViewModel):

    <%= Html.EditorForModel("SomeControl") %>
    

    instead of

    <% Html.RenderPartial("SomeControl", Model) %>
    
    0 讨论(0)
  • 2021-01-06 11:40

    Your View Model needs a default constructor without parameters and you need public set methods for each of the properties. The default model binder uses the public setters to populate the object.


    The default model binder has some rules it follows. It chooses what data to bind to in the following order:

    1. Form parameters from a post
    2. Url route data defined by your route definitions in global.asax.cs
    3. Query string parameters

    The default model binder then uses several strategies to bind to models/parameters in your action methods:

    1. Exact name matches
    2. Matches with prefix.name where prefix is the parent class and name is the subclass/property
    3. Name without prefix (as long as there are no collisions you don't have to worry about providing the prefix)

    You can override the behavior with several options from the Bind attribute. These include:

    • [Bind(Prefix = "someprefix")] -- Forces a map to a specific parent class identified by the prefix.
    • [Bind(Include = "val1, val2")] -- Whitelist of names to bind to
    • [Bind(Exclude = "val1, val2")] -- Names to exclude from default behavior
    0 讨论(0)
  • 2021-01-06 11:44

    Make a default constructor for your viewmodel and initialize the Category there

    public CategoryFormViewModel() 
    { 
        Category = new Category()
    }
    

    And at your controller action receive the viewmodel

    public ActionResult ActionName(CategoryFormViewModel model)
    {
        //here you can access model.Category.Title
    }
    
    0 讨论(0)
提交回复
热议问题