如何将局部视图渲染为字符串?

时间:2012-06-15 08:33:59

标签: c# asp.net asp.net-mvc asp.net-mvc-3 partial-views

如何从控制器或外部类库中的其他方法调用Html.Partial()方法?

我需要类似的东西:

string someView = "SomeView";
object someModel = new SomeModel();    
HtmlHelper helper = new HtmlHelper();    
string html = helper.Partial(someView, someModel).ToString();

我需要获取此方法返回的html字符串。

2 个答案:

答案 0 :(得分:2)

如果要将部分视图呈现为字符串,可以使用以下链接:Render a view as a string

但我觉得你做错了什么......

答案 1 :(得分:1)

您需要使用WebClient下载html页面,如下所示:

string viewUrl = Url.RouteUrl(new { Controller = "Pages", Action = "Index" });

WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
string result = client.DownloadString(new Uri(viewUrl ));

然后你会得到页面的html