I have this model class:
using System;
using System.ComponentModel.DataAnnotations;
namespace MvcApplication1.Models
{
public class PropertyModel
{
public int Id { get; set; }
public String BuildingStyle { get; set; }
public int BuiltYear { get; set; }
[Range(1, 100000000, ErrorMessage = "Price must be between 1 and 100,000,000.")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:0,0}")]
[Display(Name = "Price")]
public int Price { get; set; }
public string AgentName { get; set; }
}
}
And this controller:
using System.Web.Mvc;
using MvcApplication1.Models;`
namespace MvcApplication1.Controllers
{
public class PropertyController : Controller
{
public ActionResult Edit()
{
PropertyModel model = new PropertyModel
{
AgentName = "John Doe",
BuildingStyle = "Colonial",
BuiltYear = 1978,
Price = 650000,
Id = 1
};
return View(model);
}
[HttpPost]
public ActionResult Edit(PropertyModel model)
{
if (ModelState.IsValid)
{
//Save property info.
}
return View(model);
}
}
}
And this view:
@model MvcApplication1.Models.PropertyModel
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (@Html.BeginForm())
{
<text>Built Year: </text>@Html.TextBoxFor(m => m.BuiltYear)<br />
<text>Building Style: </text>@Html.TextBoxFor(m => m.BuildingStyle)<br />
<text>Agent Name: </text>@Html.TextBoxFor(m => m.AgentName)<br />
<text>Price: </text>@Html.TextBoxFor(m => m.Price)<br />
<input type="submit" value="Save" />
}
If I enter the price without any commas, ModelState.IsValid is true. But if I enter the price as a comma delimited value, ModelState.IsValid is false (see the screenshot). What do I need to do in order to be able to enter numeric values with commas and pass the model validation? I know implementing my own custom model binder is an option, but I want to make that the last option. Thank you. Please share your thoughts.