I have a custom model binding:
using System.Web.Mvc;
using MyProject.Model;
namespace MyProject.ModelBinders
{
public class VersionedIdModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
//Not completely happy with this. What if the parameter was named something besides id?
return VersionedId.Parse(bindingContext.ValueProvider["id"].RawValue.ToString());
}
}
}
which works as long as the id is passed in the url (either explicitly or via a route definition.) However, if the Id is passed in a form as a hidden input field:
<input type="hidden" id="id" name="id" value="12a" />
Then ValueProvider["id"].RawValue is a string array, so the code below doesn't behave as expected.
In the controller code, I expect to simply be able to do:
public ActionResult MyAction(VersionedId id)
{
...
}
Two questions:
- I am surprised that passing the id via form post causes the RawValue to be a string array. Is this the expected behavior, and is the "standard" way to handle this to check the type of the RawValue? I need to be able to handle both form posts and url routes.
- Is it normal to check for the Name of the parameter in the model binder, or is there another way to do this whereby the controller action can use whatever parameter name it likes?