渲染局部视图,而无需创建一个ActionResult [英] Render partial view without creating an ActionResult

查看:98
本文介绍了渲染局部视图,而无需创建一个ActionResult的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的控制器

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ShowPartial()
        {
            return PartialView("_View1");
        }
    }

这是我的索引视图

<script type="text/javascript">
    function myFunction() {
        $("#div1").load('@Url.Action("ShowPartial", "Home")');
    }
</script>
<div id="div1">
</div>
@section footerButton {
    <input type="button" id="button1" value="button" onclick="myFunction()" />
}

这是我的布局页

<body>
    <div style="height: 10%; background-color: whitesmoke; text-align: center">
        Header
    </div>
    <div style="height: 80%; background-color: white; text-align: center">
        @RenderBody()
    </div>
    <div style="height: 10%; background-color: whitesmoke; text-align: center">
        @RenderSection("footerButton", false)
    </div>
</body>

我创造,我写了一个单词你好的局部视图页面。
我做渲染上按一下按钮的局部视图。
我用命名ShowPartial,你可以看到它上面一个ActionResult。
现在我的问题是,我想相同的输出,而无需创建一个ActionResult。
请帮助。

I have created a partial view page where I have written a word "Hello". I done rendering the partial view on button click. I have used an actionResult named ShowPartial as you can see it above. Now my problem is that i want the same output without creating an Actionresult. Please help.

推荐答案

如果您返回一个字符串,而不是你可以使用以下方法来生成的字符串是一个ActionResult的。你可以任选,把基本控制器上的这个方法,让你最大限度地重复使用。

If you return a String instead of an ActionResult you could use the following to generate the string. You can, optionally, put this method on a base controller so that you maximize re-use.

public string RenderPartialViewToString(string viewName, object model)
{
    this.ViewData.Model = model;
    try
    {
        using (StringWriter sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(this.ControllerContext, viewName);
            ViewContext viewContext = new ViewContext(this.ControllerContext, viewResult.View, this.ViewData, this.TempData, sw);
            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
    }
    catch (System.Exception ex)
    {
        return ex.ToString();
    }
}

和,然后你从你的方法,这样称呼它:

and, then you call it from your method as such:

public String ShowPartial()
{
    return RenderPartialViewToString("_View1", null);
}

这篇关于渲染局部视图,而无需创建一个ActionResult的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆