2009-08-03 177 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)。

享受!