Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render partial views located on remote server

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.

like image 598
mehr Avatar asked Jan 09 '23 13:01

mehr


1 Answers

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.

like image 171
haim770 Avatar answered Jan 21 '23 08:01

haim770