ASP.NET MVC 2 以两种不同方式表示同一模型的方法是什么
例如,我有一个模型 X,其属性为 Title(string) 和 Valid(bool)。我需要在具有不同字段标签和输入控件的两个单独页面上显示相同的模型。 例如,“Title”表示标题,“Valid”表示在一种表格上有效,“Destination”表示标题,“Returning”表示在另一种表格上有效。
我想最简单的方法是对同一模型有两种不同的视图。但这真的是一种 MVC 方式吗?
谢谢
For instance I have a model X with properties Title(string) and Valid(bool). I need to show same model on two separate pages with different field labels and input controls.
E.g. "Title" for title and "Valid" for valid on one form while "Destination" for title and "Returning" for valid on the other.
I guess the easiest way would be to have two different views for the same model. But is it really a MVC way to go?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,假设您有一些名为“列表”的视图文件夹,还有一个名为“详细信息”的视图文件夹 - 并且两者中显示的模型应该不同。
您可以在这两个文件夹中分别创建一个 DisplayTemplates 文件夹,并创建一个与您的模型同名的 PartialControl,并将其强类型化到您的模型中。
在不同的视图中,您可以执行
<%= Html.DisplayFor( your model) %>
或者您也可以使用常规<% Html.RenderParital("NameOfPartial",模型X); %>
编辑
要尝试解决原始问题,也许这可以在某种程度上帮助您(我将其发布为另一个问题的答案 如何在控制器中更改 [DisplayName“xxx”]?)
也许您可以重写自定义属性来执行某种基于逻辑的名称选择,并且如何对两个模型变体使用相同的 PartialView?
Well, let's say you have some View-folder called List, and one called Details - and displaying the Model in the two should be different.
You can create a DisplayTemplates folder within each of the two folders, and create a PartialControl with the same name as your Model, and also strongly type it to your Model.
In your different views you can then do
<%= Html.DisplayFor( your model) %>
or you can also use the regular<% Html.RenderParital("NameOfPartial", ModelX); %>
Edit
To try and approach the original question, maybe this could help you in some way (I posted this as an answer to a different question How to change [DisplayName“xxx”] in Controller?)
Maybe you could rewrite the custom-attribute to do some sort of logic-based Name-selection, and that way use the same PartialView for both model-variations?
是的,两个不同的视图是合适的,因为您提供模型的两个不同视图。
但是,您确定您没有将数据硬塞到单个模型中,而实际上它在每种情况下代表不同的实体?
Yes, two different Views is appropriate, as you are providing two different VIEWS of your MODEL.
However, are you sure you aren't shoehorning your data into a single model, when in fact it represents a different entity in each case?
真的是同一个型号吗?
如果它们是具有相似属性的两个不同实体,那么我将创建两个单独的视图模型。任何共性都可以放入抽象基类或接口中。
如果它是相同的模型,但只是不同的输入屏幕,那么当然可以重用该模型。
我想第一个案例可能与这里相关。
Is it really the same model?
If they're two different entities with similar properties then I would create two separate view models. Any commonality could be put in an abstract base class or interface.
If it's the same model but just a different input screen then sure, reuse the model.
I would imagine the first case is probably the one that is relevant here.