I have a server that holds some partial view files. How i can to load files to Html.Partial from another server ? Like:
@Html.Partial("http://localhost/PartialServer/view/calculator.cshtml");
Can i override the partial to load it from url ?
Asp.net MVC is the framework.
First, create a new directory named _RemotePartialsCache
under your ~/Views/
folder.
Extend HtmlHelper
with a RemotePartial
method:
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);
// save to cache
_remotePartialsMappingCache[partialUrl] = partialLocalName;
return helper.Partial(_remotePartialsPath + partialLocalName, model);
}
}
Then use it as follows:
@Html.RemotePartial("http://localhost/PartialServer/view/calculator.cshtml")
You can also replace the original Partial
method with the above implementation (that will get to work only when the passed path is a remote url) but it's not recommended.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With