2012-07-23 22 views
0

我想在同一個視圖上使用相似功能的兩個提交表單,其中每個表單強制類型爲相同模型。然後我試圖添加一個日期選擇器到兩個表單上的相同輸入,但我不確定如何執行此操作。這裏是我的代碼:添加jQuery到MVC3中使用相同模型的表單

@using (@Ajax.BeginForm(... 
         new { id = "editScheduleForm" })) 
{ 
    <div class="editor-label"> 
     @Html.LabelFor(model => model.StartTime) 
    </div> 
    <div class="editor-field"> 
     <input 
     @Html.EditorFor(model => model.StartTime) 
     @Html.ValidationMessageFor(model => model.StartTime) 
    </div> 
} 

...

這些形式
@using (@Ajax.BeginForm(... 
         new { id = "addScheduleForm" })) 
{ 
    <div class="editor-label"> 
     @Html.LabelFor(model => model.StartTime) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.StartTime) 
     @Html.ValidationMessageFor(model => model.StartTime) 
    </div> 
} 

兩者都是在自己的強類型的局部視圖。我很自然地試圖簡單地增加jQuery中的日期選擇器這兩個部分的觀點,就像這樣:

$(function() { 
    $("#StartTime").datepicker(); 
}); 

但勿庸置疑只是工作的一個輸入。我一直在嘗試使用添加到Ajax表單聲明(例如editScheduleForm和addScheduleForm)的HTML標識,但我不確定如何執行此操作。有什麼建議麼?

解決方案: 正如scottm建議的,我查閱了使用自定義編輯器模板的文檔。我讀了這一點,細節功能我不知道的: http://msdn.microsoft.com/en-us/library/ee407399.aspx

在這裏,你可以指定一個模板,然後添加一個參數爲htmlFieldName,這是專門設計來規避我發生了什麼問題。

回答

3

您可以在編輯器模板的輸入中添加一個類。然後你可以使用該類作爲jQuery選擇器。

添加一個名爲DateTime.cshtml~/Views/Shared/EditorTemplates下的文件,並添加以下內容:

@model DateTime 
@Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "date" }) 

然後這個jQuery添加到網頁。

$(function() { 
    $(".date").datepicker(); 
}); 
+0

這將是巨大的,如果這個工作,但我不認爲我可以從'@ Html.BeginForm'手工設置類。輸出的HTML已經有一個類,如下所示:' c0nn 2012-07-23 18:13:41

+0

@ c0nn您可以通過在'〜/ Views/Shared/EditorTemplates'中添加一個.cshtml文件來進一步定義編輯器模板的渲染方式。下面是一個例子,它完全符合你的要求:http://geekswithblogs.net/michelotti/archive/2010/02/05/mvc-2-editor-template-with-datetime.aspx – scottm 2012-07-23 18:20:19

+0

完美,這將很好地工作。謝謝。 – c0nn 2012-07-23 18:29:05

0

The ID must be unique in a document.

決不依賴於多個IDS工作正常的網頁上。事實上,儘管博客中大多數例子都是這樣做的,但您幾乎不應該使用ID作爲jQuery選擇器。

就像@scottm說的。您應該使用類來標記您想要進行構件化的項目。

下面是一個代碼簡單一點,所以你可以聲明創建JQ UI部件:

在你的HTML
$(function() { 

    $('[data-usewidget]').each(function() { 
    var $this = $(this), widget = $this.data('usewidget'); 
    $.fn[widget] && $this[widget](); 
    }); 

}); 

然後

<input name=startTime data-usewidget=datepicker /> 
相關問題