有這個問題並沒有內置的機制,但你可以建立一個自定義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; }
謝謝,這有點我正在尋找 – user3182508