2012-05-26 48 views
1

我找不到在MVC3中使用JQuery日期選擇器的完整解決方案,並且從我在不同頁面上找到的解決方案中找到了解決方案,但仍然無法正常工作。 我有以下幾點:MVC3中的JQuery日期選擇器奇怪的行爲

型號:

public class Some 
{ 
    [Display(Name = "DateCreated", ResourceType = typeof(Resources))] 
    [Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName =  "RequiredField")] 
    [DataType(DataType.Date, ErrorMessage = "Date non valid.")] 
    [DisplayFormat(NullDisplayText = "NotSpecified", DataFormatString = "{0:dd.MM.yyyy.}")] 
    public DateTime DateCreated { get; set; } 
} 

我裝修的財產,因爲我想在客戶端和服務器端驗證和文字。

我使用的這個例子中,家庭控制器和我有:

public ActionResult Index() 
    { 
     Some model = new Some { DateCreated = DateTime.Now }; 

     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(Some model) 
    { 
     if (ModelState.IsValid) 
     { 
      return RedirectToAction("Index"); 
     } 

     return View(model); 
    } 

的觀點:

@model TestDatePicker.Models.Some 

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

    <p> 
     <input type="submit" value="Save" /> 
    </p> 
} 

並與DateTime類型渲染領域的自定義模板:

@model Nullable<System.DateTime> 

@{ 
    string controlName = ViewData.TemplateInfo.HtmlFieldPrefix; 
    string controlId = controlName.Replace(".", "_"); 

    if (Model.HasValue) { 
     @Html.TextBox("", String.Format("{0:dd.MM.yyyy.}", Model.Value), new { @class = "textbox", name = controlName }) 
    } 
    else { 
     @Html.TextBox("", String.Format("{0:dd.MM.yyyy.}", DateTime.Now), new { @class = "textbox", name = controlName }) 
    } 
    } 

} 
<script type="text/javascript"> 
    $(document).ready(function() { 

     $(".textbox").datepicker 
      ({ 
       dateFormat: 'dd.mm.yy.', 
       showStatus: true, 
       showWeeks: true, 
       highlightWeek: true, 
       numberOfMonths: 1, 
       showAnim: "scale", 
       showOptions: { 
        origin: ["top", "left"] 
       }, 
       onClose: function() { 
        $(this).valid(); 
       } 
      }); 
    }); 
</script> 

此代碼發生了什麼? DateTime字段的值將在自定義模板中分配,並顯示爲當天的日期。

  1. 然而,單擊保存按鈕,在[HttpPost] Index方法我看到模型通過未持有當天日期的價值,但1/1/0001 12:00:00 AM?
  2. 然後Model.IsValid不會傳遞消息值'26.05.2012'。對於創建的日期無效。 ???對我來說似乎更陌生!
  3. 顯示上述消息的頁面,而不是我的自定義消息上: [數據類型(DataType.Date,的ErrorMessage =「日期不有效」)

有趣的是,如果你使用的日期選擇器並從中選擇一個數據,您將獲得模型中填充的屬性。而Model.IsValid是TRUE。

這是輸入控件的HTML的樣子:

<input class="textbox" data-val="true" data-val-required="Requred field" id="DateCreated" name="DateCreated" type="text" value="26.05.2012." /> 

This is on page load

This is when just clicking Save after page loads

This is the result, not taking my custom error message assigned to Model

是jQueryUI的日期選擇器不是ASP的最佳選擇。 NET MVC?看來,這個我在網上看到的自定義模板的解決方案,基本的MVC的東西甚至沒有工作?有沒有人知道這樣做的任何完整的教程?我不能成爲面臨這些問題的第一人。

謝謝。

我已經下載了在the blog post大家創建的代碼是指在談論MVC3和日期選擇器,同樣的事情正在發生的事情有什麼時候!

回答

2

即使世界在你的模板什麼,你的模型和您提供的日期時間值之間的結合。
當表單被引用時,mvc需要知道如何用表單中的值填充Some對象。這適用於標準編輯器,因爲它們使用綁定的標籤名稱作爲客戶端輸入的標識/名稱。你沒有用你的自定義編輯器來做到這一點,因此當表單被冒用時,mvc不會告訴你的自定義編輯器實際提供DateCreated屬性。
將名稱/ id屬性添加到編輯器中的底層輸入中,以使其工作(或使用標準提供的編輯器,並查看瀏覽器中的ur頁面的html源代碼/任何類型的網絡嗅探器以查看它是如何工作的)

編輯:我的代碼的完整版,即工程
型號:

public class Some 
{ 
    [Display(Name = "DateCreated")]  
    [Required(ErrorMessage="failed")]  
    [DataType(DataType.Date, ErrorMessage = "Date non valid.")]  
    [DisplayFormat(NullDisplayText = "NotSpecified", DataFormatString = "{0:dd.MM.yyyy.}")]  
    public DateTime DateCreated { get; set; } } 

控制器:

public class DefaultController : Controller 
{ 
    public ActionResult Index() 
    { 
     Some model = new Some { DateCreated = DateTime.Now }; 
     return View(model); 
    } 
    [HttpPost] 
    public ActionResult Index(Some model) 
    { 
     if (ModelState.IsValid) 
     { 
      return RedirectToAction("Index"); 
     } 
     return View(model); 
    } 

} 

索引視圖:

@model Some 
@using (Html.BeginForm()) 
{ 
     <div class="editor-label">  
     @Html.LabelFor(model => model.DateCreated) 
     </div> 
     <div class="editor-field">  
     @Html.EditorFor(model => model.DateCreated) 
     @Html.ValidationMessageFor(model => model.DateCreated) 
     </div>  
     <p>  
     <input type="submit" value="Save" /> 
     </p> 
} 

日編輯:

@model Nullable<DateTime> 
@{  
    string controlName = ViewData.TemplateInfo.HtmlFieldPrefix;  
    string controlId = controlName.Replace(".", "_");  
    if (Model.HasValue) 
    {   
     @Html.TextBox("", String.Format("{0:dd.MM.yyyy.}", Model.Value), 
     new {@class "textbox", name = controlName })  
    }  
    else 
    {   
    @Html.TextBox("", String.Format("{0:dd.MM.yyyy.}", DateTime.Now), 
    new { @class = "textbox", name = controlName })  
    } 
} 

      <script type="text/javascript"> 
       $(document).ready(function() { 
        $(".textbox").datepicker({ 
         dateFormat: 'dd.mm.yy.', 
         showStatus: true, 
         showWeeks: true, 
         highlightWeek: true, 
         numberOfMonths: 1, 
         showAnim: "scale", 
         showOptions: { origin: ["top", "left"] }, 
         onClose: function() { $(this).valid(); } 
        }); 
       }); 
       </script> 

包括腳本:

<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" 
    type="text/javascript"></script> 
    <script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" 
    type="text/javascript"></script> 
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" 
    type="text/javascript"></script> 
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" 
    type="text/javascript"></script> 

它在我身邊工作的100%,與我們沒有jQuery的日期選擇器。我稍微改變了屬性的用法,並沒有爲它們提供資源。據我瞭解,順便說一句,DataType屬性在這種情況下是無用的。

+0

感謝您的回答。請看看我編輯的模板以及我爲id屬性添加的更改。我沒有解決這個問題。 – elector

+1

它的名字,你需要,而不是id(id主要用於JavaScript)。你是否也添加了它? name屬性是http的世界中用來標識表單字段的東西,當它們被引用到thr服務器時。 [這篇文章](http://develoq.net/2011/asp-net-mvc-model-binders-and-how-to-create-custom-model-binder/)解釋了這一點,我相信。 – YavgenyP

+0

感謝這篇文章,這是一個很好的資源。我對該評論投了一票。請查看我的問題中更新的代碼。我認爲,從datepicker中選擇一個值後,頁面的第一次加載需要一些「黑客入侵」的原因。 – elector