我有一个要求,我需要将来自View的HTML数据保存在字符串变量中,就像这样
string data = GetData(Id)
和GetData是一个返回View的方法
public ActionResult GetData(int Id)
{
return PartialView("ViewName");
}
我的要求是将此视图创建/返回的内容作为HTML分配给string
变量data
实际上可能吗?
感谢您的帮助
答案 0 :(得分:1)
试试这个
public static string GetTemplateContentInstance(ControllerContext controllerContext, string viewName, object model)
{
if (string.IsNullOrWhiteSpace(viewName))
//Return name of view for current action
viewName = controllerContext.RouteData.GetRequiredString("action");
controllerContext.Controller.ViewData.Model = model;
using (StringWriter stringWriter = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);
ViewContext viewContext = new ViewContext(controllerContext, viewResult.View, controllerContext.Controller.ViewData, controllerContext.Controller.TempData, stringWriter);
viewResult.View.Render(viewContext, stringWriter);
return stringWriter.GetStringBuilder().ToString();
}
}
使用如下
string viewBody = GetTemplateContentInstance(this.ControllerContext, Url.Content("ViewName"), ModelName)
答案 1 :(得分:0)
试试这个:
private string GetHtmlFromUrl(string url)
{
string html = "";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// get the response stream.
//Stream responseStream = response.GetResponseStream();
// use a stream reader that understands UTF8
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
html = reader.ReadToEnd();
// close the reader
reader.Close();
response.Close();
return html;//return content html
}
用法:
string data = GetHtmlFromURL("/YourController/GetData/{ID}")
//or GetHtmlFromURL("/YourController/GetData?ID={ID}") if your route isn't set to accept ID
答案 2 :(得分:0)
您尝试创建HtmlHelper的实例并在该帮助程序中使用RenderPartial扩展方法
注意:您需要在System.Web.Mvc.Html中包含一个使用来访问RenderPartial
public static HtmlHelper GetHtmlHelper( this Controller controller )
{
var viewContext = new ViewContext( controller.ControllerContext, new FakeView(), controller.ViewData, controller.TempData, TextWriter.Null );
new HtmlHelper( viewContext, new ViewPage() ).RenderPartial("/mypartial");
}
public class FakeView : IView
{
public void Render( ViewContext viewContext, TextWriter writer )
{
throw new InvalidOperationException();
}
}