2012-11-22 30 views
2

我正在開發像嚮導一樣的步驟(控制器),並使用DerivedModel1,DerivedModel2等從BaseModel繼承,並擴展它們的額外屬性。 只有模型的數據,沒有業務邏輯。所有由控制器中的服務執行的邏輯操作,例如_step1Service.GetRelated(model.id)。asp.net mvc在每個操作之前修復(更正)數據。在模型或控制器中執行?

現在我想不只是驗證模型(這種情況下,有ValidationAttribute),但修復無效數據BaseModel

public class BaseModel 
{ 
    public DateTime StartDate {get;set;} 
} 

StartDate應大於今天。用戶可以選擇無效日期而不是驗證錯誤應用程序應該修復此值(重置爲默認值?)。

在我第一次嘗試我的驗證/糾錯StartDate,並在每個行動呼籲增值服務:

public ActionResult Index(DerivedModel1 model) 
{ 
_svc.fixModel(model); 

if(!ModelState.IsValid) 
{ 
return View(); 
} 

... do stuff with valid data 
} 

但不喜歡這樣,因爲有這一行添加到每個控制器和動作。 然後我把這個更正加到StartDate二傳手。它看起來更好,但這打破了流行的MVC範式,所有的邏輯都應該在控制器中(或者我誤解了某些東西?) 我在想這個問題的可能解決方案:ActionFilterAttribute,定製ModelBinder?但不知道這是正確的方式,是否工作。 你對此有何想法?

+0

如果你要允許對諸如'StartDate'之類的數據進行寬鬆的驗證,爲什麼不這樣做,而不是默認任意值或者進行抨擊離子,只允許整個模型中的空值(例如,使StartDate成爲'Nullable '並在數據庫中對此進行調整。我寧願知道我沒有數據,也不知道有沒有意義/不值得信任的有效數據? – StuartLC

+0

可以有另一個驗證規則,'fixModel'不應該修復(依賴於其他輸入,用戶自己校正數據非常重要)。 StartDate不能爲空,它是嚮導中的主要選項。有這個字段的JavaScript驗證,所以用戶不能選擇無效的日期,但我也想在服務器端添加驗證。 – user1407492

回答

1

您必須實現IModelBinder來實現此目的。

先定義你的自定義模型粘合劑是這樣的:

public class MyCustomModelBinder : IModelBinder 
{ 
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
     { 
      // Get the raw attempted value from the value provider 
      DateTime incomingDate = (DateTime) bindingContext.ValueProvider.GetValue("datefield").AttemptedValue; 
      //validate and correct date here ... 
      return new BaseModel{ DateMember = incomingDate }; 
     } 
} 

然後註冊您的自定義模型粘合劑,例如:

protected void Application_Start() 
{ 
     ModelBinders.Binders.Add(typeof (BaseModel), new MyCustomModelBinder());   
} 

和控制器:

public ActionResult YourAction([ModelBinder(typeof(MyCustomModelBinder)] BaseModel model) 
{ 
     return Content("Ok"); 
} 
+0

所以我必須爲DerivedModel1和DerivedModel2添加'ModelBinder'?或者根據活頁夾中的規則創建派生模型,然後投入使用? – user1407492

+0

它取決於你,你可以做任何一種方式。 –

0

驗證和業務規則有區別。對象可以(並且通常應該)負責確保它們本身處於有效狀態。

+0

是的,我可以爲模型驗證添加驗證屬性。但也想重置無效值爲有效 - 這是業務規則嗎? – user1407492

相關問題