获取字符串形式的MVC partialView/View数据

本文关键字:partialView View 数据 MVC 字符串 获取 | 更新日期: 2023-09-27 18:13:56

我有一个要求,我需要从视图的HTML数据保存在一个字符串变量,像这样

string data = GetData(Id)

和GetData是一个方法,它返回视图,如

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

我的要求是得到任何这个视图创建/返回作为HTML分配给string变量data

这真的可能吗?

Thanks for Help

获取字符串形式的MVC partialView/View数据

试试这个

 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)

试试这个:

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

你尝试创建一个HtmlHelper的实例,并在该helper中使用RenderPartial扩展方法

注意:你需要包含一个using到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();
            }
        }