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

时间:2014-04-16 02:40:08

标签: c# asp.net-mvc 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" />
}

enter image description here

如果我输入的价格没有任何逗号,则ModelState.IsValid为true。但是如果我以逗号分隔值的形式输入价格,则ModelState.IsValid为false(请参见屏幕截图)。为了能够用逗号输入数值并传递模型验证,我需要做什么?我知道实现我自己的自定义模型绑定器是一个选项,但我想让它成为最后一个选项。谢谢。请分享您的想法。

3 个答案:

答案 0 :(得分:2)

这是问题所在:

public int Price { get; set; }

原因是您的价格已设为int。如果你放一个逗号,它会导致错误。如果您想要逗号,只需将int更改为string,然后如果您要将其用于计算,只需使用split[',']分割逗号并将其转换为{{1使用int方法。

答案 1 :(得分:2)

您使用的是哪个版本的MVC?

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

答案 2 :(得分:1)

您需要将Price的数据类型更改为字符串,以便通过验证。通过这样做,你将不得不做一些额外的检查,看看传入的字符串是否真的是一个有效的int。一点额外的工作,但不是太糟糕。