下面是返回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();
解决方法
您可以使用此方法,从控制器传递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(); }