2011-12-01 72 views
1

我有一個包含幾個輸入字段的輸入表單。每個輸入字段都有一個ElementModel,它具有基本上用於標籤和值的屬性。要顯示的輸入字段是在XML文檔中指定的,所以我只有一個動態視圖,只有一列元素。在MVC中使用抽象視圖模型3

問題是,每個元素應顯示爲小數或百分比值。當然,如果它是一個百分比值,用戶應該能夠輸入「45%」之類的東西,模型中的值應該是0.45。

我時,我發現this文章首先想到的是用一個抽象的視圖模型類的抽象屬性的值,並定義一個PercentageElementModel從我的基地派生ElementModel類,使得使用自定義模型粘合劑。不幸的是,如果我在我的視圖中使用抽象基類,則在PercentageElementModel中所做的數據註釋將被忽略。

你對我如何解決這個問題有任何想法嗎?我不想在我的視圖模型中使用字符串,並且自己進行解析,因爲這會破壞MVC模式。有其他方法可以實現我的目標嗎?

下面是一些代碼片段:

public abstract class ElementModel 
{ 
    public string ElementName { get; set; } 

    public ElementType ElementType { get; set; } 

    public abstract double? ElementValue { get; set; } 
} 

public class PercentageElementModel : ElementModel 
{ 
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:P2}")] 
    public override double? ElementValue { get; set; } 
} 
+0

我最近在這個問題的答案中詳細解決了這個問題:[在MVC3中使用強類型視圖時可能的模型繼承?](http://stackoverflow.com/questions/8311907/model-inheritance-possible -when-strong-strong-typed-view-in-mvc3/8320821#8320821) – counsellorben

+0

@Andrew Barber,我強烈反對你對FAQ的理解。這是對類似問題的答案的鏈接。它從根本上回答了OP的問題,因此不應該轉換爲評論。請查閱您引用的常見問題指南。 – counsellorben

+0

@counsellorben感謝您的鏈接,這完全回答了我的問題。其實,我發現了另一個也符合我需求的解決方案。我會在這裏發佈它作爲答案) – tbmsu

回答

0

我想出了另一種解決方案,我的問題是更多的顯示格式比驗證的問題:我寫了一個自定義的模型綁定器,它檢查文本輸入字符串框。如果以結尾的'%'符號結尾,我會將值除以100.這是代碼。

public class DoubleModelBinder : IModelBinder 
    { 
     public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
     { 
      var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); 
      var modelState = new ModelState { Value = valueResult }; 

      double? actualValue = null; 
      try 
      { 
       // cut trailing '%' 
       if (valueResult.AttemptedValue.EndsWith("%")) 
       { 
        var strValue = valueResult.AttemptedValue.Substring(0, valueResult.AttemptedValue.Length - 1); 
        actualValue = double.Parse(strValue, valueResult.Culture)/100; 
       } 
       else 
       { 
        actualValue = Convert.ToDouble(valueResult.AttemptedValue, CultureInfo.CurrentCulture); 
       } 
      } 
      catch (FormatException e) 
      { 
       modelState.Errors.Add(e); 
      } 

      bindingContext.ModelState.Add(bindingContext.ModelName, modelState); 
      return actualValue; 
     } 
    } 

其餘發生在視圖本身。要顯示正確的格式,我使用一個簡單的ToString()方法,並根據需要指定一個百分比格式字符串。如果用戶輸入的數字值不含'%',jQuery的blur()事件將在用戶的輸入中附加'%'符號。完美的爲我工作,雖然這不是我自己的問題的最佳答案。