我有這樣的模型類:逗號分隔數值在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爲true。但是,如果我將價格輸入爲逗號分隔值,則ModelState.IsValid爲false(請參閱屏幕截圖)。爲了能夠用逗號輸入數值並通過模型驗證,我需要做什麼?我知道實施我自己的自定義模型聯編程序是一個選項,但是我想將其作爲最後一個選項。謝謝。請分享你的想法。
謝謝。我有點不情願將數據類型更改爲字符串。它應該是一個數字數據類型。 – Stack0verflow
我明白了。但是,如果您確實需要逗號,則必須將其用作字符串並將其手動轉換爲int或使用自定義ModelBinder。我不確定你還可以做什麼。 – jensendp
客戶堅持擁有逗號功能,所以我別無選擇。我想知道我是否可以這樣做:爲輸入定義公共字符串PriceAsString,並定義public int Price,它在內部將PriceAsString轉換爲int。所以,視圖會有@ Html.TextBoxFor(m => m.PriceAsString)。但是,這可能也意味着我將無法使用[Range(1,100000000)]開箱即可批註PriceAsString,並且必須執行一些自定義驗證。 – Stack0verflow