asp.net-mvc - 如何获取 View html并返回客户端

标签 asp.net-mvc

下面是将 View 返回到 jquery 函数的代码片段,但我想知道如何提取或获取 View html 并返回到客户端。

$(function() {
   $('#myddl').change(function() {
       var url = $(this).data('url');
       var value = $(this).val();
       $('#result').load(url, { value: value })
    });
});

<div id="result"></div>

在 Foo 操作中,您可以返回部分 View :
public ActionResult Foo(string value)
{
    SomeModel model = ...
    return PartialView(model);
}

在网络表单中,我以这种方式提取用户控件或任何与 html 相关的控件。
System.Web.UI.Page pageHolder = new System.Web.UI.Page();
BBAReman.facebox.FeedBack ctl = (BBAReman.facebox.FeedBack)pageHolder.LoadControl("~/UserControls/FeedBack.ascx");
System.Web.UI.HtmlControls.HtmlForm tempForm = new System.Web.UI.HtmlControls.HtmlForm();
tempForm.Controls.Add(ctl);
pageHolder.Controls.Add(tempForm);
StringWriter output = new StringWriter();
HttpContext.Current.Server.Execute(pageHolder, output, false);
outputToReturn = output.ToString();

那么如何在 mvc 中做同样的事情。只是想知道如何从操作方法中获取 View html。谢谢

最佳答案

您可以使用此方法,从 Controller 传递 ActionResult 并从 View 中取回 html

    private string RenderActionResultToString(ActionResult result)
    {
        // Create memory writer.
        var sb = new StringBuilder();
        var memWriter = new StringWriter(sb);

        // Create fake http context to render the view.
        var fakeResponse = new HttpResponse(memWriter);
        var fakeContext = new HttpContext(System.Web.HttpContext.Current.Request,
            fakeResponse);
        var fakeControllerContext = new ControllerContext(
            new HttpContextWrapper(fakeContext),
            this.ControllerContext.RouteData,
            this.ControllerContext.Controller);
        var oldContext = System.Web.HttpContext.Current;
        System.Web.HttpContext.Current = fakeContext;

        // Render the view.
        result.ExecuteResult(fakeControllerContext);

        // Restore old context.
        System.Web.HttpContext.Current = oldContext;

        // Flush memory and return output.
        memWriter.Flush();
        return sb.ToString();
    }

关于asp.net-mvc - 如何获取 View html并返回客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18335402/

相关文章:

c# - 如何在 Razor 中修复此 "syntax error"?

javascript - 在引导模式窗口内设置部分 View

javascript - 无法对元素 : not a valid selector 执行匹配

c# - 如何使用 MVC 4 应用程序运行 Asp.net Webforms 网站

asp.net-mvc - Fluent NHibernate 和存储库模式

c# - 带有 For 循环内表单的 MVC View 提交空模型

asp.net-mvc - 在 ASP.NET MVC 中使用 Chart helper 时如何更改饼图的默认颜色

jquery - MVC JQuery DatePicker 无法在 ie 中工作(在 Chrome 中工作)

asp.net-mvc - ActionResult 重定向使用 ToString() 呈现

c# - 侧边栏中带有标题列表的新闻页面