MVC3剃刀编辑/显示模板和泛型 [英] MVC3 Razor Editor/Display templates and generics
问题描述
有关于MVC的模板和泛型的一些问题却似乎有没有涉及到什么我要找的。请考虑以下型号:
There were a few questions regarding mvc templates and generics however there seems to be none related to what I'm looking for. Consider the following models:
namespace MyNamespace
{
public class ModelBase { /* Not important for example */ }
public class MyModel : ModelBase
{
public string Name { get; set; }
}
public class MyViewModel
{
public IEnumerable<ModelBase> Data { get; set; }
}
}
和控制器:
public class HomeController : Controller
{
public ActionResult Index
{
return View(new MyViewModel { Data = new List<MyModel>() })
}
}
一个的Razor视图查看/主页/ Index.cshtml看起来像:
A Razor view Views/Home/Index.cshtml would look like:
@model MyNamespace.MyViewModel
@Html.EditorFor(m => m.Data)
没什么特别的存在。如果我想显示器或编辑模板,我可以创建视图下的文件/共享/ EditorTemplate或在查看/主页/ EditorTemplates称为MyModel.cshtml并正确找到它。
Nothing special there. If I want a display or editor template for that I can create a file under Views/Shared/EditorTemplate or under Views/Home/EditorTemplates called MyModel.cshtml and it finds it correctly.
如果我想要做的事对模型库的每个实现不同的显示列表时? MVC取景器将在上述任何路径正确找到List'1.cshtml模板。不过我需要做的是做List`1 [为MyModel] .cshtml
What if I want to do something different for each implementation of ModelBase when showing a list? Mvc view finder will find List'1.cshtml template correctly in any of above paths. However what I need to do is do a template for List`1[MyModel].cshtml
我似乎无法得到正确的文件命名。我到目前为止已经试过(相对于这个例子命名):
I can't seem to get the correct file naming. What I've tried so far (relative to this example naming):
- List`1 [为MyModel] .cshtml
- List`1 [为MyModel]。CSHTML
- List`1 [MyNamespace.MyModel] .cshtml
- List`1 [MyNamespace.MyModel]。CSHTML
如果可能,我想避免编写自定义取景器。我能想到的,现在,如果我不能得到上面的东西来工作的唯一选择是只List`1.cshtml调用部分从列表命名推导出来。
If possible I want to avoid writing a custom view finder. The only alternative I can think of for now if I can't get above stuff to work is to just have List`1.cshtml call a partial with naming deduced from List.
推荐答案
我没有检查这个code,但我会为每个亚型不同的看法,做喜欢的事,愚蠢的:
I haven't checked this code but I would create different Views for each subtype and do something dumb like:
return View(MyModel.GetType().Name, new MyViewModel { Data = new List<MyModel>() })
这样你的视图相匹配的类型的名称。
So that your View matches the name of your type.
这篇关于MVC3剃刀编辑/显示模板和泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!