2014-04-16 28 views
0

我有這樣的模型類:逗號分隔數值在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(請參閱屏幕截圖)。爲了能夠用逗號輸入數值並通過模型驗證,我需要做什麼?我知道實施我自己的自定義模型聯編程序是一個選項,但是我想將其作爲最後一個選項。謝謝。請分享你的想法。

回答

1

您需要將價格的數據類型更改爲字符串,以便通過驗證。通過這樣做,你將不得不做一些額外的檢查,看看傳入的字符串是一個真正有效的int。有點額外的工作,但不是太糟糕。

+0

謝謝。我有點不情願將數據類型更改爲字符串。它應該是一個數字數據類型。 – Stack0verflow

+1

我明白了。但是,如果您確實需要逗號,則必須將其用作字符串並將其手動轉換爲int或使用自定義ModelBinder。我不確定你還可以做什麼。 – jensendp

+0

客戶堅持擁有逗號功能,所以我別無選擇。我想知道我是否可以這樣做:爲輸入定義公共字符串PriceAsString,並定義public int Price,它在內部將PriceAsString轉換爲int。所以,視圖會有@ Html.TextBoxFor(m => m.PriceAsString)。但是,這可能也意味着我將無法使用[Range(1,100000000)]開箱即可批註PriceAsString,並且必須執行一些自定義驗證。 – Stack0verflow

2

這就是問題所在:

public int Price { get; set; } 

原因是你的價格設置成int。如果您放置逗號,它會導致錯誤。如果你想要一個逗號,只需要將你的int改爲string,那麼如果你打算用它來進行計算,只需使用split[',']來分割逗號並使用Convert.ToInt32()方法將其轉換爲int

+0

謝謝,但是如果我將數據類型更改爲字符串,我將無法使用一些開箱即用的int註釋,例如[Range(1,100000000)],正確嗎? – Stack0verflow

2

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

當你顯示價格文本的逗號時,我建議你應該使用自定義的ModelBinder來獲取它的值。

+1

這個問題的標題說它是MVC4。是的,我可以像我提到的那樣自定義ModelBinder,但是我想讓它成爲最後一個選項。 – Stack0verflow

+0

所以我決定實現我自己的自定義模型綁定器。但我遇到了問題。我有一個問題在這裏:http://stackoverflow.com/questions/23145780/asp-net-mvc-4-how-to-validate-my-model-in-a-custom-model-binder。你可以看一下嗎?謝謝。 – Stack0verflow