使用 Html.RenderPartial 渲染派生部分视图

发布于 2024-08-25 06:53:08 字数 542 浏览 11 评论 0原文

如果 MyControl.ascx 是直接继承 System.Web.Mvc.ViewUserControl< 的控件,则从视图调用 Html.RenderPartial("~/Views/Payments/MyControl.ascx"); 是有效的/代码>。

但是,如果控件继承从 System.Web.Mvc.ViewUserControl 派生的新类,则调用 Html.RenderPartial("~/Views/Payments /MyDerivedControl.ascx"); 失败,报告不存在此类视图。

派生示例 System.Web.Mvc.ViewUserControl

class MyDerivedControl : System.Web.Mvc.ViewUserControl
{
    public Method()
    {
        ViewData["SomeData"] = "test";
    }
}

是否有解决方法,或者是否有其他方法可以做到这一点?也许是 HTML 助手?

Calling Html.RenderPartial("~/Views/Payments/MyControl.ascx"); from a view works if MyControl.ascx is a control that directly inherits System.Web.Mvc.ViewUserControl.

However, if the control inherits a new class that derives from System.Web.Mvc.ViewUserControl, the call to Html.RenderPartial("~/Views/Payments/MyDerivedControl.ascx"); fails, reporting that no such view exists.

Example derived System.Web.Mvc.ViewUserControl:

class MyDerivedControl : System.Web.Mvc.ViewUserControl
{
    public Method()
    {
        ViewData["SomeData"] = "test";
    }
}

Is there a workaround, or is there another way I should be doing this? Perhaps an HTML helper?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吹梦到西洲 2024-09-01 06:53:08

从 MVC 的角度来看,让视图提供数据并不是一个好的设计。通常这是控制器的责任。根据上下文以及该数据所代表的内容,您可以使用 HTML 帮助程序或编写操作过滤器。这是一个带有自定义操作过滤器的示例:

public class SomeDataActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);
        filterContext.Controller.ViewData["SomeData"] = "test";
    }
}

然后用此过滤器装饰您的操作:

[SomeDataActionFilter]
public ActionResult Index()
{
    return View();
}

From MVC point of view it is not a good design to have your view provide data. Usually this is the responsibility of the controller. Depending on the context and what this data represents you could use an HTML helper or a write an action filter. Here's an example with a custom action filter:

public class SomeDataActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);
        filterContext.Controller.ViewData["SomeData"] = "test";
    }
}

And then decorate your action with this filter:

[SomeDataActionFilter]
public ActionResult Index()
{
    return View();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文