EditorFor 확장 메서드 (MVC2)와 함께 사용할 List`1 편집기 템플릿을 작성했지만 generics + null 개체를 사용할 때 문제가 발생합니다. 제네릭을 사용하여 ASP.NET MVC보기/부분
는 모델class MyModel {
public Foo SomeFoo { get;set; }
public List<Foo> SomeFooList { get;set; }
}
내가 SomeFoo에 대한 예상 편집기를 얻을
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%
IEnumerable enumerableModel;
if (Model != null && (enumerableModel = Model as IEnumerable) != null)
{
foreach (var v in enumerableModel)
{
var model = v;
Response.Write(Html.EditorFor(m => model));
}
}
%>
/Views/Shared/EditorTemplates/List`1.ascx
에서 템플릿 및 SomeFooList의 어떤 요소를 감안할 때 ModelMetaData의 형식은 "Foo"이므로 null이 아닙니다. 그러나 SomeFooList의 객체 중 하나 인 "null"이있는 경우 모델이 "object"유형이고 Foo가 아닌 일반적으로 T의 일반 인수에서 나오는 T는 렌더링되지 않습니다.기본적으로 나는
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<T>> where T : class" %>
그래서 난 내 목록의 유형을 알고
처럼 뭔가를 달성하고 싶습니다.null의 경우 ModelMetaData.ModelType 필드를 변경할 수도 있습니다 (새 객체를 만들 때 읽기 전용이므로). 그러나 이것은 피할 수없는 불쾌한 해킹 중 하나입니다.
또 다른 생각은 .Invoke를 사용하여 EditorFor 메서드를 호출하고 거기에 typeof (T)를 전달하는 것이지만 가능한 경우이 유형의 코드를 피하고 싶습니다.
의견이 있으십니까?
업데이트 : 모델 메타 데이터로 유형을 얻기 위해 노력
가 처음 예상했던 것보다 조금 더 까다 찾고 있었다. 나는 작동하는 것 같다 다음에 내 코드를 업데이트,하지만 난 여전히 solition 너무 치열하지 않다 :
if (Model != null && (enumerableModel = Model as IEnumerable) != null)
{
Type listType = null;
if (enumerableModel.GetType().IsGenericType)
{
listType = enumerableModel.GetType().GetGenericArguments()[0];
}
foreach (var v in enumerableModel)
{
var model = v;
if (model == null && listType != null)
model = Activator.CreateInstance(listType);
Response.Write(Html.EditorFor(m => model));
}
}
아마르
어쩌면
그건 그렇고, 어떤 사람이 Nullable < T >을 공백에 넣지 않고이 마크 다운에 제대로 쓰는 방법을 보여줄 수 있다면, 나는 위대 할 것입니다! – Charlie
백틱 ('\'') 안에 넣으면'Nullable'이됩니다. –
LukeH
그것은 공정한 것처럼 보인다, 나는 내일 이것과 연극을 가지고 내가 그것으로부터 무엇이라도 얻을 수 있는지 알 것이다. 건배 – amarsuperstar