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
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) %>
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:
The default model binder then uses several strategies to bind to models/parameters in your action methods:
You can override the behavior with several options from the Bind attribute. These include:
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
}