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

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 如何获取视图html并返回客户端前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
下面是返回jquery函数视图的代码片段,但我想知道如何提取获取视图html并返回到客户端.
$(function() {
   $('#myddl').change(function() {
       var url = $(this).data('url');
       var value = $(this).val();
       $('#result').load(url,{ value: value })
    });
});

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

在Foo动作中你可以返回一个局部视图:

public ActionResult Foo(string value)
{
    SomeModel model = ...
    return PartialView(model);
}

在web形式这种方式我延长usercontrols或任何控件相关的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中做同样的事情.我想知道如何从动作方法获取视图html.谢谢

解决方法

您可以使用此方法,从控制器传递ActionResult并从视图中返回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相关文章