Rendering External Views In ASP.NET MVC
This is a post from the archives. Probably don't do this.
See more archived posts in the archives.
Sometimes you need to consume a partial view that's been exposed by another MVC application. You could call the external partial view method via JavaScript or you could call it via your MVC application. Below are two helpers for consuming external partial views in MVC.
The first helper renders the external response directly to response stream. The second helper returns a MvcHtmlString. Note, both methods are POC and do not have proper checks and error handling.
Render External View Helper:
public static void RenderExternalView(this HtmlHelper helper, string uri) {
if (!string.IsNullOrEmpty(uri)) {
using (var client = new WebClient()) {
// Pass something in the request header to identify the caller
client.Headers["X-Requested-With"] = "RenderExternalView";
// Depending on your environment, you may need to set credentials
/*client.Credentials = CredentialCache.DefaultCredentials;
client.Proxy = WebRequest.GetSystemWebProxy();
client.Proxy.Credentials = CredentialCache.DefaultCredentials;*/
// Render the view directly into the Response writer
helper.ViewContext.Writer.Write(client.DownloadString(uri));
}
}
}
External View Helper:
public static MvcHtmlString ExternalView(this HtmlHelper helper, string uri) {
if (!string.IsNullOrEmpty(uri)) {
using (var client = new WebClient()) {
// Pass something in the request header to identify the caller
client.Headers["X-Requested-With"] = "ExternalView";
// Depending on your environment, you may need to set credentials
/*client.Credentials = CredentialCache.DefaultCredentials;
client.Proxy = WebRequest.GetSystemWebProxy();
client.Proxy.Credentials = CredentialCache.DefaultCredentials;*/
// Return a string in include in the view
return new MvcHtmlString(client.DownloadString(uri));
}
}
return new MvcHtmlString(string.Empty);
}