ASP.NET MVC Model Binding with Dashes in Form Element Names
asp.net-mvc, c#, model-binding, model-view-controller
Solution
You could always create your own model binder.
Here's an example that implements a binder that supports adding Aliases to model properties:
http://ole.michelsen.dk/blog/bind-a-model-property-to-a-different-named-query-string-field/
And with it do something like:
[ModelBinder(typeof(AliasModelBinder))]
public class Person
{
[BindAlias("first-name")]
public string FirstName { get; set; }
[BindAlias("last-name")]
public string LastName { get; set; }
//etc...
}
EDIT: This implementation, as the blogger says, is based on Andras' answer on the following SO question: Asp.Net MVC 2 - Bind a model's property to a different named value
Problem
I have been scouring the internet trying to find a way to accomodate dashes from my form elements into the default model binding behavior of ASP.NET's Controllers in MVC 2, 3, or even 4. As a front-end developer, I prefer dashes in my CSS over camelCase or underscores. In my markup, what I want to be able to do to is something like this: ``` <input type="text" name="first-name" class="required" /> <input type="text" name="last-name" class="required" /> ``` In the controller, I would be passing in a C# object that would look like this: ``` public class Person { public string FirstName { get; set; } public string LastName { get; set; } //etc... } ``` Is there some way to extend the `Controller` class to accommodate this through some regex or other behavior? I hate the fact that I have to do something like this: ``` <input type="text" name="person.firstname" class="required" /> ``` or even this: ``` <input type="text" name="isPersonAttending" class="required" /> ``` Thoughts?