I currently have:
@Html.EditorFor(model => model.PurchasePrice)
I would like to split this into 2 separate fields separated by a decimal (for price input obviously). But if I do that using basic text boxes I will loose the ability to take advantage of ASP.NET’s validation.
Is there a way to do this, in Razor or by using attributes, so that I am able to keep the JS and server-side validation against my Entity model?
I can easily do it somewhere else by creating my own functions within the viewmodel, but I’m new to MVC3 and not entirely sure if that would be the best route or there is a simpler method.
Edit:
This is kind of the direction I am thinking, I do not fully understand how this works.
I set 2 fields, 1 as ppDollar and 1 as ppCents. In the controller I have:
modelname.PurchasePrice = Request["ppDollar"] + Request["ppCent"];
But, I can look at that and tell that’s not going to work. So, I guess the question really is how is user input validated against the entity model and how can I better take advantage of the built in functionality?
You can create custom editors for particular types that are rendered by
EditorFor. You can find a lot of examples of how to do this online, most of them focusing on a customDateTimeeditor but the same idea applies to any type. Just one example from a quick search:http://buildstarted.com/2010/09/10/overriding-displayfor-and-editorfor-to-create-custom-outputs-for-mvc/
In short, the process is:
Views\Shared\EditorTemplatesfolder, with the same name as the type (e.g.Decimal.cshtml).@inherits System.Web.Mvc.WebViewPage<System.Decimal>EditorForoverload, referenced in your template through theViewData.ModelMetadata.AdditionalValuesproperty.One thing to note: once you define an editor template it will be used for every call to
EditorFor. You can scope them to a specific controller by moving theEditorTemplatesfolder into the appropriate view subfolder instead of the shared one.