2011-09-24 49 views
4

我有一個需要DateTime的控制器操作?通過查詢字符串作爲post-redirect-get的一部分。控制器看起來像例如MVC3,Razor視圖,EditorFor,查詢字符串值覆蓋模型值

public class HomeController : Controller 
{ 
    [HttpGet] 
    public ActionResult Index(DateTime? date) 
    { 
     IndexModel model = new IndexModel(); 

     if (date.HasValue) 
     { 
      model.Date = (DateTime)date; 
     } 
     else 
     { 
      model.Date = DateTime.Now; 
     } 

     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(IndexModel model) 
    { 
     if (ModelState.IsValid) 
     { 
      return RedirectToAction("Index", new { date = model.Date.ToString("yyyy-MM-dd hh:mm:ss") }); 
     } 
     else 
     { 
      return View(model); 
     } 
    } 
} 

我的模型是:

public class IndexModel 
{ 
    [DataType(DataType.Date)] 
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd MMM yyyy}")] 
    public DateTime Date { get; set; } 
} 

而剃刀的看法是:

@model Mvc3Playground.Models.Home.IndexModel 

@using (Html.BeginForm()) { 
    @Html.EditorFor(m => m.Date); 
    <input type="submit" /> 
} 

我的問題是雙重的:

(1)日期格式施加在如果查詢字符串包含日期值,則使用[DisplayFormat]屬性的模型不起作用。 (2)模型中保存的值似乎被查詢字符串值包含的值覆蓋。例如。如果我在Index GET操作方法中設置了一個斷點,並且手動設置日期等於今天說,如果查詢字符串包含例如?date = 1/1/1,則在文本框中顯示「1/1/1」(計劃將驗證日期,如果查詢字符串無效,則默認它)。

任何想法?

回答

14

HTML輔助結合,所以當第一次使用的ModelState如果你打算修改一些值,它是存在於控制器動作內部模型的狀態確保您從ModelState中首先除去它:

[HttpGet] 
public ActionResult Index(DateTime? date) 
{ 
    IndexModel model = new IndexModel(); 

    if (date.HasValue) 
    { 
     // Remove the date variable present in the modelstate which has a wrong format 
     // and which will be used by the html helpers such as TextBoxFor 
     ModelState.Remove("date"); 
     model.Date = (DateTime)date; 
    } 
    else 
    { 
     model.Date = DateTime.Now; 
    } 

    return View(model); 
} 

我必須同意這種行爲不是很直觀,但它是通過設計讓人們真正適應它。

這裏發生了什麼:

  • 當你請求/首頁/索引裏面什麼也沒有的ModelState所以Html.EditorFor(x => x.Date)助手使用您的視圖模型(您已設置爲DateTime.Now)的價值,當然它適用正確的格式
  • 當你請求/Home/Index?date=1/1/1,該Html.EditorFor(x => x.Date)幫助檢測到有內部ModelState等於1/1/1一個date變量,並使用這個值,完全無視存儲您的視圖模型中(這是相當多的條款Ø相同的值f日期時間值,但當然不應用格式)。
+0

啊 - 真棒的答案,非常感謝:-) – magritte

相關問題