2014-04-01 19 views
0

後,我有一個觀點這是一個要求日期復位日期時間輸入框爲空失敗ModelState.IsValid

如果用戶離開這個空白的輸入框,ModelState回報false和模型返回到視圖。

然而,在這種情況下,DateTime場,然後與價值DateTime.MinValue(01/01/0001)

如何從模型中清除該值,並返回一個空白輸入框填充?

感謝

回答

1

如果你還沒有驗證,然後在模型定義日期nullable

DateTime? AnyDate {get; set;} 

所以問題就解決了。當用戶沒有輸入AnyDate時,發佈後會是null。如果它不起作用,你可以寫作:

if (!ModelState.IsValid) 
{ 
    //control for any case 
    if(model.AnyDate == DateTime.MinValue) model.AnyDate = null;  
} 
+0

這就是我最終做的 - 我沒有意識到,我可以有一個[必須的]註釋的空屬性...現在如果有沒有輸入傳遞給控制器​​的值爲null,並且驗證失敗 - 謝謝! – iabbott

0

一旦你POST-ING回你看來,你將需要使用SetModelValue()方法來操縱你的ModelState(不是你的模型)的值。或者,您可能會違反條目,但這具有其他含義(即損壞ModelStateDictionary對象中的模型)。

例如,如果你的數據元素被稱爲RequiredDateTime,那麼你的控制器代碼可能是:

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult ThisAction(int id, YourModel model) 
{ 
    // Process the 'IsValid == true' condition 
    if (ModelState.IsValid) 
    { 
     // ... 
     return RedirectToAction("NextAction"); 
    } 

    // Process the 'IsValid == false' condition 
    if (ModelState.ContainsKey("RequiredDateTime")) 
    { 
     ModelState.SetModelValue("RequiredDateTime", new ValueProviderResult(...)); 
    } 

    // ... 

    return View(model); 
} 

編輯

一點點額外的研究打開了下面,還看到:

MVC - How to change the value of a textbox in a post?

How to modify posted form data within controller action before sending to view?

我希望這會有所幫助。祝你好運!

0

如果要返回空值,你必須編輯模型的實體可空如下:

public Class MyObject 
{ 
    String parameter {get; set;} 
    DateTime? time {get; set;} 
} 

如果你想改變用戶輸入前重新渲染頁面的值與領域,你有如下修改的模型對象DateTime.MinValue(例如):

public ActionResult MyMethod(MyObject model) 
    { 
    if (ModelState.IsValid) 
     { 
     ... 
     } 
    else 
     { 
     model.time = DateTime.MinValue; 
     } 
    return View(model); 
    } 
相關問題