尝试将模型传递给部分模型,我该怎么做?
我的操作创建了一个强类型的视图数据,它被传递到我的视图。
在视图中,我将模型传递给渲染部分方法。
public ActionResult Index()
{
ViewDataForIndex vd = new ViewDataForIndex();
vd.Users = Users.GetAll();
return View(vd);
}
public class ViewDataForIndex: ViewData
{
public IList<User> Users {get;set;}
}
现在在视图中:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ViewDataForIndex>" %>
<% Html.RenderPartial("~/controls/blah.ascx", ViewData.Model); %>
和 blah.ascx 中:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
- 我现在如何访问我的模型?
- 如果我想为 ViewUserControl 创建一个强类型类,我该怎么做?继承自?
My action creates a strongly typed viewdata, which is passed to my view.
In the view, I pass the Model to the render partial method.
public ActionResult Index()
{
ViewDataForIndex vd = new ViewDataForIndex();
vd.Users = Users.GetAll();
return View(vd);
}
public class ViewDataForIndex: ViewData
{
public IList<User> Users {get;set;}
}
now in the view:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ViewDataForIndex>" %>
<% Html.RenderPartial("~/controls/blah.ascx", ViewData.Model); %>
and in blah.ascx:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
- how do I access my model now?
- if I wanted to create a strongly typed class for my ViewUserControl, how would I do that? inherit from?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一:在 ascx 内部:
二:向 ViewUserControl 提供类型参数:
One: Inside the ascx:
Two: Provide a type Argument to ViewUserControl:
我更喜欢 @jfar 的第二种方法,因为如果您决定将更复杂的模型传递给视图,它可以更轻松地进行修改。
因此,您可以传递一个具有多个属性和/或更多子对象的类。
如果您现在从该对象继承,那么您所需要做的就是从复杂对象继承并更改一段代码,以及添加新属性,然后就完成了。
I like @jfar's second approach better as it allows for easier modification if you ever decide to pass a more complex model to the view.
So you may pass a class that has multiple properties and/or more child objects.
If you inherit from the object now, then all you need to do is to inherit from your complex object and change one piece of code, as well as add the new properties, and your done.
更具体地说,jfar 的答案:
如果您的父页面具有
ViewDataForIndex
类型的模型,则使用相同的ViewData.Model
调用子页面也将传递类型的对象ViewDataForIndex
。More specifically to jfar's answer:
If your parent page has a model of type
ViewDataForIndex
, calling the child with the sameViewData.Model
will also pass an object of typeViewDataForIndex
.