逗号分隔数值在asp.net验证失败MVC 4 [英] Comma delimited numeric value fails validation in asp.net MVC 4

查看:118
本文介绍了逗号分隔数值在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是假的(见截图)。我需要做什么才能做能够与逗号输入数值,并通过模型验证?我知道实现自己的自定义模型粘合剂是一种选择,但我想做出最后的选择。谢谢。请分享你的看法。

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.

推荐答案

您正在使用的MVC的版本?

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.

这篇关于逗号分隔数值在asp.net验证失败MVC 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆