0

我有一个要求,我需要将 View 中的 HTML 数据保存在字符串变量中,就像这样

string data = GetData(Id)

GetData 是一种返回 View 的方法

public ActionResult GetData(int Id) { return PartialView("ViewName"); }

我的要求是将此视图创建/返回的任何内容作为 HTML 分配给string变量data

真的有可能吗?

感谢帮助

4

3 回答 3

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)
于 2013-05-15T14:58:11.910 回答
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
于 2013-05-15T13:59:00.577 回答
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();
            }
        }
于 2013-05-15T14:07:37.620 回答