Consider an HTML form built in the following way:
<select name="schoolType">
@foreach (SchoolType schoolType in Model.SchoolTypes)
{
<option value="@schoolType.Id">@schoolType.Name</option>
}
</select>
Now, SchoolType is a model class. It’s designed in my EDMX for Entity Framework.
In the above scenario, right now, my action method looks like this:
public ActionResult CreateSchool(int schoolType)
{
...
SchoolType myType = container.SchoolTypeSet.FirstOrDefault(t => t.Id == schoolType);
...
}
Would it be possible to program some kind of helper so that MVC would automatically know to convert the integer into a Model class with that ID, like the following action method signature?
public ActionResult CreateSchool(SchoolType schoolType)
{
...
}
You can use a ModelBinder to accomplish this:
Where your Model Binder looks like:
You can also associate binders with types globally at startup:
resulting in the nice, clean action you requested: