2011-02-18 4 views
7

최근 ASP.NET MVC 표시 템플릿으로 문제가 발생했습니다. 말이 내 모델이 컨트롤러입니다문자열 용 ASP.NET MVC 표시 템플릿이 정수로 사용됩니다.

public class Model 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
} 

:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     return View(new Model()); 
    } 
} 

이 내이다 :

내가 어떤 이유로 모든 문자열의 표시 템플릿을해야하는 경우
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<DisplayTemplateWoes.Models.Model>" %> 

<!DOCTYPE html> 

<html> 
<head runat="server"> 
    <title>Index</title> 
</head> 
<body> 
    <div> 
     <%: Html.DisplayForModel() %> 
    </div> 
</body> 
</html> 

다음과 같이 String.ascx 부분 뷰를 생성합니다 :

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %> 

<%: Model %> (<%: Model.Length %>) 

그리고 여기에 문제가 있습니다 - 런타임에 다음 예외가 throw됩니다. "사전에 전달 된 모델 항목의 형식은 'System.Int32'이지만이 사전에는 'System.String'형식의 모델 항목이 필요합니다."

String.ascx가 Model 클래스의 정수 및 문자열 속성에 사용 된 것 같습니다. 문자열 속성에만 사용되기를 기대했는데, 결국 Object.ascx 나 Int32.ascx가 아닌 String.ascx로 명명되었습니다. 이것은 의도적으로 설계된 것입니까? 그렇다면 - 어딘가에 문서화되어 있습니까? 그렇지 않은 경우 - 버그로 간주 될 수 있습니까?

답변

4

이것은 디자인적인 것 같습니다. 더 일반적인 문자열 템플릿을 만들어야합니다. 문자열 템플릿은 자체 템플릿이없는 모든 복잡한 모델에 기본 템플릿으로 사용됩니다. 문자열에 대한

기본 템플릿 (FormattedModelValue 객체이다) :

internal static string StringTemplate(HtmlHelper html) { 
    return html.Encode(html.ViewContext.ViewData.TemplateInfo.FormattedModelValue); 
} 

템플릿 선택은 다음과 같습니다

foreach (string templateHint in templateHints.Where(s => !String.IsNullOrEmpty(s))) { 
    yield return templateHint; 
} 

// We don't want to search for Nullable<T>, we want to search for T (which should handle both T and Nullable<T>) 
Type fieldType = Nullable.GetUnderlyingType(metadata.RealModelType) ?? metadata.RealModelType; 

// TODO: Make better string names for generic types 
yield return fieldType.Name; 

if (!metadata.IsComplexType) { 
    yield return "String"; 
} 
else if (fieldType.IsInterface) { 
    if (typeof(IEnumerable).IsAssignableFrom(fieldType)) { 
     yield return "Collection"; 
    } 

    yield return "Object"; 
} 
else { 
    bool isEnumerable = typeof(IEnumerable).IsAssignableFrom(fieldType); 

    while (true) { 
     fieldType = fieldType.BaseType; 
     if (fieldType == null) 
      break; 

     if (isEnumerable && fieldType == typeof(Object)) { 
      yield return "Collection"; 
     } 

     yield return fieldType.Name; 
    } 
} 

을 그래서 당신은 단지 문자열 템플릿을 만들려면, 당신처럼해야 this (String.ascx) :

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<object>" %> 

<% var model = Model as string; %> 
<% if (model != null) { %> 
    <%: model %> (<%: model.Length %>) 
<% } else { %> 
    <%: Model %> 
<% } %> 
관련 문제