Which is the right MVC way to create custom form control (like custom drop down)? I need a way to create such control and re-use it in few pages. I want to use default binder to bind the selected value when action method is called. Can someone give a simple example how this is done?
Here is my current solution which by my opinion is not designed very well.
DropDownViewModel.cs
class DropDownViewModel {
...
public string BindName {get; set;} // the name that default binder uses to bind to action param
public int SelectedValue {get;set;} // this value should be set when user use the drop down
...
}
DropDown.ascx
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DropDownViewModel>" %>
...
<%= Html.TextBox(Model.BindName) %>
...
The problem comes when I try to include this DropDownViewModel into some other view model like this one:
GeneralUserInfoViewModel.cs
class GeneralUserInfoViewModel {
...
public DropDownViewModel Gender {get;set;}
...
}
AccountController.cs
...
public ActionResult EditGeneralUserInfo(GeneralUserInfoViewModel info) {
}
...
This to work properly BindName should be set to "Gender.SelectedValue". This can be resolved by setting BindName in RegisterUserViewModel. But what happen if GeneralUserInfoViewModel is part of another view model like:
RegisterUserViewModel.cs
class RegisterUserViewModel {
...
public GeneralUserInfoViewModel GeneralInfo {get;set;}
...
}
Now the BindName should be set to "GeneralInfo.Gender.SelectedValue" in order this to work properly with default binder:
...
public ActionResult RegisterUser(RegisterUserViewModel info) { ... }
...
and etc. How this layering can be handled? How can I determine what should be set to BindName attr in DropDownVoewModel? Or is there another better way to implement it?