【发布时间】:2014-04-16 02:40:07
【问题描述】:
我有这个模型类:
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(请参见屏幕截图)。为了能够用逗号输入数值并通过模型验证,我需要做什么?我知道实现我自己的自定义模型绑定器是一个选项,但我想将其作为最后一个选项。谢谢你。请分享您的想法。
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-4