繁体   English   中英

逗号分隔的数值在 asp.net MVC 4 中验证失败

[英]Comma delimited numeric value fails validation in asp.net MVC 4

我有这个模型类:

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; }
    }
}

而这个控制器:

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);
        }         
    }
}

而这个观点:

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

在此处输入图片说明

如果我输入不带任何逗号的价格,则 ModelState.IsValid 为真。 但是,如果我以逗号分隔值的形式输入价格,则 ModelState.IsValid 为 false(请参见屏幕截图)。 我需要做什么才能使用逗号输入数值并通过模型验证? 我知道实现我自己的自定义模型绑定器是一种选择,但我想把它作为最后一个选择。 谢谢你。 请分享您的想法。

这就是问题:

public int Price { get; set; }

原因是您的价格设置为int 如果放置逗号,它将定义错误导致错误。 如果要使用逗号,只需将int更改为string然后如果要使用它进行计算,则只需使用split[',']拆分逗号,并使用Convert.ToInt32()方法将其转换为int

您正在使用哪个版本的MVC?

在显示价格文本的逗号时,建议您使用自定义ModelBinder获取其值。

您需要将Price的数据类型更改为字符串,以使其通过验证。 通过这样做,您将不得不做一些额外的检查,以查看传入的字符串确实是有效的int。 有点额外的工作,但还不错。

成功代码在这里http://blog.rebuildall.net/2011/03/02/jQuery_validate_and_the_comma_decimal_separator

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

在视图中(javascript)->

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM