You could write a custom model binder for the corresponding view model:
public class MyViewModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
bindingContext.ModelName = "some_prefix";
return base.BindModel(controllerContext, bindingContext);
}
}
which you could register in your Application_Start
and associate with your view model:
ModelBinders.Binders.Add(typeof(MyViewModel), new MyViewModelBinder());
In this example, I have hardcoded the prefix, but you could make the model binder a bit more generic and reusable and take into account the BindAttribute
that you could use to decorate your view model with:
public class MyViewModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
// TODO: cache the result of this LINQ query to
// avoid using reflecting on each request. After all
// the metadata of the view model won't change at runtime
var bindAttribute = bindingContext
.ModelType
.GetCustomAttributes(typeof(BindAttribute), true)
.OfType<BindAttribute>()
.FirstOrDefault();
bindingContext.ModelName = bindAttribute != null ? bindAttribute.Prefix : null;
return base.BindModel(controllerContext, bindingContext);
}
}
and then all that's left is to decorate your view model with the Bind attribute:
[Bind(Prefix = "some_prefix")]
public class MyViewModel
{
public string Foo { get; set; }
public string Bar { get; set; }
}
and request the action that is taking this view model:
/someaction?some_prefix.foo=the_foo_value&some_prefix.bar=the_bar_value