Show partial views located on a remote server
1 answer
First create a new directory named _RemotePartialsCache
in the folder ~/Views/
.
Extend HtmlHelper
with method RemotePartial
:
public static class HtmlExtensions
{
private const string _remotePartialsPath = "~/Views/_RemotePartialsCache/";
private static readonly IDictionary<string, string> _remotePartialsMappingCache = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
public static MvcHtmlString RemotePartial(this HtmlHelper helper, string partialUrl, object model = null)
{
string cachedPath;
// return cached copy if exists
if (_remotePartialsMappingCache.TryGetValue(partialUrl, out cachedPath))
return helper.Partial(_remotePartialsPath + cachedPath, model);
// download remote data
var webClient = new WebClient();
var partialUri = new Uri(partialUrl);
var partialData = webClient.DownloadString(partialUrl);
// save cached copy locally
var partialLocalName = Path.ChangeExtension(partialUri.LocalPath.Replace('/', '_'), "cshtml");
var partialMappedPath = helper.ViewContext.RequestContext.HttpContext.Server.MapPath(_remotePartialsPath + partialLocalName);
File.WriteAllText(partialMappedPath, partialData);
// add to cache
_remotePartialsMappingCache.Add(partialUrl, partialLocalName);
return helper.Partial(_remotePartialsPath + partialLocalName, model);
}
}
Then use it like this:
@Html.RemotePartial("http://localhost/PartialServer/view/calculator.cshtml")
You can also replace the original method Partial
with the above implementation (which will only work when the passed path is a remote url), but this is not recommended.
+4
source to share