2012-11-15 16 views
0

使用MVC3和jQuery插件datepicker。在MVC3中獲取日期時間總是返回給控制器

我可以看到日曆,我可以設置日期到現場。但是當我將模型發回控制器時,我總是得到屬性的空值。它將該特定日期顯示爲無效日期。

這是我的模特。我的看法

@using (Html.BeginForm()) 
{ 
    @Html.ValidationSummary(true) 

    <fieldset> 
    <legend>BlogPost</legend> 

    <div class="editor-label"> 
    @Html.LabelFor(model => model.PostTitle) 
    </div> 
    <div class="editor-field"> 
    @Html.EditorFor(model => model.PostTitle) 
    @Html.ValidationMessageFor(model => model.PostTitle) 
    </div> 

    <div class="editor-label"> 
    @Html.LabelFor(model => model.PostTime) 
    </div> 
    <div class="editor-field"> 
    <span class="datepicker"> 
    @Html.EditorFor(model => model.PostTime) 
    @Html.ValidationMessageFor(model => model.PostTime) 
    </span> 
    </div> 


    <p> 
    <input type="submit" value="Create" /> 
    </p> 
    </fieldset> 
} 

    <script src="http://code.jquery.com/jquery-1.8.2.js"></script> 
     <script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script> 
     <script type="text/javascript"> 
      $(document).ready(function() { 
       $("#PostTime").datepicker({ 
        showOn: 'both', 
        buttonImage: "/content/img/calendar_icon.png" 
       }); 
      }); 
     </script> 

控制器

[DataType(DataType.DateTime)] 
     [DisplayName("PostTime")] 
     [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] 
     public DateTime? PostTime { get; set; } 

而且部分是

[HttpPost] 
public ActionResult Create(BlogPost blogpost) 
{ 
    if (ModelState.IsValid) 
    { 
     var db = new BlogPostContext(); 
     db.Add(blogpost); 
     return RedirectToAction("Index"); 
    } 
    return View(blogpost); 
} 

有人可以什麼我失蹤。

謝謝。

+0

使用你的代碼,我無法獲取模型返回一個空值。你可以將你的Controller動作添加到問題中,以便我可以看到該代碼在做什麼? – samazi

+0

@SandorA更新了我的問題。 – Naresh

回答

1

至於得到一個錯誤說這是不是一個有效日期,就需要指定日期選擇器的格式:

 $(document).ready(function() { 
      $("#PostTime").datepicker({ 
       showOn: 'both', 
       dateFormat: 'dd/mm/yy', 
       buttonImage: "/content/img/calendar_icon.png" 
      }); 
     }); 
+0

也嘗試過。但它不起作用。通過上述格式,我可以獲得'11/November/20122012'的價值。 – Naresh

+0

更新了格式,假設你想要11/11/2012 – ethorn10

+0

它現在正在工作。但我真的不明白驗證失敗背後的邏輯。我認爲它必須以相同的格式設置和驗證日期。 – Naresh