2014-03-03 110 views
0

.net mvc5可以根據特定規則綁定屬性嗎?例如,我有一個時間輸入(例如10.30),我需要將它綁定到一個double。我希望沿着這個線的東西:綁定單個屬性的模型

// Model 
[CustomAttribute("TimeAttr")] 
public double Hours { get; set; } 

// Binding 
public TimeAttrBinder : IModelBinder 
{ 
    // Replace colons with dots 
    return double.Parse(value.Replace(':', '.')); 
} 

// Global 
ModelBinders.add("TimeAttr", TimeAttrBinder) 

所以,我可以把一個註解在模型的屬性,它的自定義模型綁定,每次...

這種事可能在.net mvc5中?

回答

1

有這個問題並沒有內置的機制,但你可以建立一個自定義PropertyBinder屬性將應用模型綁定只在一定的財產作爲本文所示:http://aboutcode.net/2011/03/12/mvc-property-binder.html

你可以把它非常通用如圖所示在文章中,但要說明這個概念,你可以嘗試這樣的事情。

元數據知道標記屬性:

public class MyMarkerAttribute : Attribute, IMetadataAware 
{ 
    public void OnMetadataCreated(ModelMetadata metadata) 
    { 
     metadata.AdditionalValues["marker"] = true; 
    } 
} 

定製模型粘結劑,將明白此標記屬性:

public class MyModelBinder : DefaultModelBinder 
{ 
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     if (bindingContext.ModelMetadata.AdditionalValues.ContainsKey(MyMarkerAttribute.MarkerKey)) 
     { 
      var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); 
      if (value != null) 
      { 
       // Here you could implement whatever custom binding logic you need 
       // for your property from the binding context 
       return value.ConvertTo(typeof(double)); 
      } 
     } 

     return base.BindModel(controllerContext, bindingContext); 
    } 
} 

,然後用自定義一個在Application_Start替換默認模型聯:

ModelBinders.Binders.DefaultBinder = new MyModelBinder(); 

這就是它。現在,您可以使用標記屬性來修飾您的視圖模型:

[MyMarker] 
public double Hours { get; set; } 
+0

謝謝,這有點我正在尋找 – user3182508