简体   繁体   English

在C#MVC 3中从Viewbag渲染局部视图

[英]Rendering a partial view from viewbag in c# mvc 3

I have a solution with two projects and I'm trying to send a partial view from one project to the other. 我有一个包含两个项目的解决方案,并且试图将一个项目的局部视图发送到另一个项目。

So in project AI have a controller like this: 所以在项目AI中有一个像这样的控制器:

    public PartialViewResult Index()
    {
        return PartialView("_Forms");
    }

And in project BI have a controller like this: 在项目BI中有一个像这样的控制器:

    public ActionResult Index()
    {

        var form = pa.Index(); // <-- This is the controller from controller A

        ViewBag.CMSForm = form;

        return View();
    }

... so far so good, but now I need to render the partial view from ViewBag.CMSForm and I can't figure out how. ...到目前为止还不错,但是现在我需要从ViewBag.CMSForm渲染部分视图,而我不知道该如何做。

If you are only trying to render the partial view... 如果您仅尝试渲染局部视图...

I was just messing with something similar to this, where I needed to render different partial views on one Index view based on where the user was routing from. 我只是在搞弄类似的东西,我需要根据用户从哪里路由,在一个Index视图上呈现不同的局部视图。

What I did was something like this... 我所做的就是这样...

public ActionResult Index()
{

    ViewBag.CMSForm = "_Forms";

    return View();
}

Then on your view 然后在您看来

@{

string form= ViewBag.CMSForm;
 }
 @section CustomForm{


@Html.Partial(form)
}

I have adapted the solution from http://craftycodeblog.com/2010/05/15/asp-net-mvc-render-partial-view-to-string/ to your case. 我已根据您的情况从http://craftycodeblog.com/2010/05/15/asp-net-mvc-render-partial-view-to-string/修改了该解决方案。

Change your code from project B to this: 将您的代码从项目B更改为此:

public ActionResult Index()
{

    var form = pa.Index(); // <-- This is the controller from controller A

    using (var sw = new StringWriter())
    {
        // Find the actual partial view.
        var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, form.ViewName);
        // Build a view context.
        var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
        // Render the view.
        viewResult.View.Render(viewContext, sw);
        // Get the string rendered.
        ViewBag.CMSForm = sw.GetStringBuilder().ToString();
    }

    return View();
}

Why not use rendering of ControllerA.Index-action in view of ControllerB? 为什么不鉴于ControllerB使用ControllerA.Index-action的呈现?

<p>
@Html.Action("Index", "ControllerA")
</p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM