1

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" />
}

enter image description here

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.

Stack0verflow
  • 1,148
  • 4
  • 18
  • 42

4 Answers4

2

This is the problem:

public int Price { get; set; }

The reason is your Price is set into int. It would definetley cause an error if you place a comma. If you want a comma, just change your int into a string then if your going to use it for computations, just use the split[','] to split the comma and convert it to int by using the Convert.ToInt32() method.

Xtian
  • 508
  • 2
  • 6
  • Thanks, but if I change the data type to string, I won't be able to use some annotations out of the box for int, such as [Range(1, 100000000)], correct? – Stack0verflow Apr 16 '14 at 14:50
2

Which version of MVC you are using ?

As you are displaying comma for price text, I suggest you should use custom ModelBinder to get its values.

dotnetstep
  • 17,065
  • 5
  • 54
  • 72
  • 1
    The title of this question says it is MVC4. Yes, I can do a custom ModelBinder as I mentioned, but I'd like to make that the last option. – Stack0verflow Apr 16 '14 at 13:38
  • So I decided to implement my own custom model binder. But I am running into issues. I have a question here: http://stackoverflow.com/questions/23145780/asp-net-mvc-4-how-to-validate-my-model-in-a-custom-model-binder . Could you take a look? Thank you. – Stack0verflow Apr 18 '14 at 00:57
1

You would need to change the data type of your Price to a string so that it would pass the validation. By doing that though, you would have to do some additional checking to see that the string passed in is truly a valid int. A little extra work, but not too bad.

jensendp
  • 2,135
  • 15
  • 15
  • Thanks. I am a little reluctant to change the data type to string. It should be a numeric data type. – Stack0verflow Apr 16 '14 at 13:37
  • 1
    I understand. But if you truly want the comma, you will either have to use it as a string and convert it to an int manually or use a custom ModelBinder. I'm not sure how else you can do it. – jensendp Apr 16 '14 at 14:23
  • The customer insisting in having the comma feature, so I have no choice. I wonder if I can do this: Define public string PriceAsString for the input, and also define public int Price, which internally converts PriceAsString to an int. So, the view would have @Html.TextBoxFor(m=>m.PriceAsString). However, this probably also means that I won't be able to annotate PriceAsString using [Range(1, 100000000)] out of the box, and have to do some custom validation. – Stack0verflow Apr 16 '14 at 14:47
  • Yes, that will accomplish the same thing. – jensendp Apr 16 '14 at 15:38
0

Success Code Here http://blog.rebuildall.net/2011/03/02/jQuery_validate_and_the_comma_decimal_separator

in Model-> [Range(1, 100000000, ErrorMessage = "Price must be between 1 and 100,000,000.")]

in View (javascript) ->

 $.validator.methods.range = function (value, element, param) {
    var globalizedValue = value.replaceAll(",", "");
    return this.optional(element) || (globalizedValue >= param[0] && 
    globalizedValue <= param[1]);
 }
Cha Mildz
  • 11
  • 2