You can try the Controller.UpdateModel or Controller.TryUpdateModel method:
[HttpPost] public ActionResult SaveStatement(User currentUser, FormCollection statement, string ViewModelName) { ... object ViewModel = Activator.CreateInstance(type); if (TryUpdateModel(viewModel)) {
However, I would suggest you create a custom ModelBinder, as it is responsible for creating and populating the model properties.
I can show you a simple example of how you can do this:
Base viewmodel
public abstract class StatementViewModel { public abstract StatementType StatementType { get; } ... } public enum StatementType { Relief, RequestForSalary, ... }
ViewModels
public class RequestForSalaryVM : StatementViewModel { public override StatementType StatementType { get { return StatementType.RequestForSalary; } } ... } public class ReliefVM : StatementViewModel { public override StatementType StatementType { get { return StatementType.Relief; } } ... }
ModelBinder
public class StatementModelBinder : DefaultModelBinder { protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) { var statementTypeParameter = bindingContext.ValueProvider.GetValue("StatementType"); if (statementTypeParameter == null) throw new InvalidOperationException("StatementType is not specified"); StatementType statementType; if (!Enum.TryParse(statementTypeParameter.AttemptedValue, true, out statementType)) throw new InvalidOperationException("Incorrect StatementType");
After that, register the model binder in Global.asax :
ModelBinders.Binders.Add(typeof(StatementViewModel), new StatementModelBinder());
controller
[HttpPost] public ActionResult Index(StatementViewModel viewModel) { if (ModelState.IsValid) {
Zabavsky
source share