2009-08-03 89 views

回答

4

我還沒有試過預覽1仍然但是他們做了什麼,你在這個Channel9的視頻要求:

http://channel9.msdn.com/posts/Glucose/Hanselminutes-on-9-ASPNET-MVC-2-Preview-1-with-Phil-Haack-and-Virtual-Scott/

他們這樣做既DisplayFor和EditorFor,開始約2分鐘。

- 編輯 -

對於價值型即詮釋我能得到它在相同的方式工作。

創建一個模型傳遞給我的看法:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     HomeModel model = new HomeModel(); 
     model.message = "Welcome to ASP.NET MVC!"; 
     model.number = 526562262; 
     model.Date = DateTime.Now; 

     return View(model); 
    } 
} 

public class HomeModel 
{ 
    public string message { get; set; } 

    public int number { get; set; } 

    public DateTime Date { get; set; } 
} 

使用新的模板邏輯鏈接視圖模型:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<HomeModel>" %> 

<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server"> 
<p> 
    <% Html.EditorFor(c => c.message); %> 
</p> 
<p> 
    <% Html.EditorFor(c => c.number); %> 
</p> 
<p> 
    <% Html.EditorFor(c => c.Date); %> 
</p> 

然後爲每個創建模板類型例如INT32:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> 
Editor For My Int32: <%= Html.TextBox("abc", Model.ToString())%> 

我把這個意見\共享\ EditorTemplates \ Int32.ascx

+0

視頻顯示基於引用類型(字符串)而非值類型創建編輯器模板。 – 2009-08-04 08:42:37

15

,當你上回發提交的值將尼克·克拉克的回答工作?

在MVC2預覽2中,調用Html.Textbox(「abc」,Model.ToString()) 將呈現名稱後附加「.abc」的文本框。

<input id="StartDate_abc" name="StartDate.abc" type="text" value="02 Feb 09" /> 

當您回發並嘗試UpdateModel()時會導致問題。

我做了一個DateTime編輯模板,對我下面的作品:

/Views/Shared/EditorTemplates/DateTime.ascx:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime>" %> 
<%= Html.TextBox(String.Empty, Model.ToString("dd MMM yy")) %> 

,或者使用jQuery的DatePicker的所有您DateTimes 將對jQuery和jQueryUI的引用添加到Masterpage或包含對EditorFor的調用的View中。

/Views/Shared/EditorTemplates/DateTime.ascx:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime>" %> 
<%= Html.TextBox("", Model.ToString("dd MMM yy")) %> 
<script type="text/javascript"> 
    $("#<%= ViewData.ModelMetadata.PropertyName %>").datepicker({ dateFormat: 'dd M y' }); 
</script> 

更新:ASP。NET MVC3,使用剃刀語法:

@model System.DateTime 
@Html.TextBox("", Model.ToString("dd MMM yy")) 
<script type="text/javascript"> 
    $("#@ViewData.ModelMetadata.PropertyName").datepicker({ dateFormat: 'dd M y' }); 
</script> 

,並使用它你在你的瀏覽需要的是:

@Html.EditorFor(model => model.DueDate) 

-Matt

2

我寫a blog post如何做這通過在MVC 2中創建可重複使用的模板。

我的文章還解釋了TemplateInfo和模板之間的關係。

1

我發現布拉德威爾遜的blog有最好的例子和解釋。該系列的Part-3專門討論值類型(String,decimal,Int32)。

享受!

相關問題