Asp.net Mvc Display template of String, but now ev

2020-07-08 07:02发布

问题:

I created a Display Template which when passed a string renders a disabled text box

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<String>" %>
<%: Html.TextBoxFor(model => model, new { disabled = "disabled" })%>

Which works great. However, for some reason MVC wants to try and stuff DateTimes and Ints through it as well, which is throwing exceptions

The model item passed into the dictionary is of type 'System.Int32', but this dictionary requires a model item of type 'System.String'.

Any ideas?

回答1:

You don't need to strongly type the template to a String.

you can try something like this :

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%= Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
             , new { disabled = "disabled" }) %>

And in your view you call it like this

Html.DisplayModelFor(model => mode.name);

For more information see an example of the default built-in editor template for the string in Brad Wilson article in his his series on Templates in ASP.NET MVC.

You should consider going through the complete series. I can't express how helpful this series was for me.