Tuesday, November 25, 2014

MVC - How to get current domain root path in javaScript variable

Problem statement:

Get current domain root path in javascript variable. In some cases, we want to redirect to domain root from client side. Below is the solution for that.

Solution:

Create property in MVC model class to return current domain (Getting this in client side may occurs some url mismatches)

public class LocalMVCModel

    {
        ...etc., your other properities

        public string CurrentDomain { get { return GetSiteRoot(); } }

        private string GetSiteRoot()
        {
            string port = System.Web.HttpContext.Current.Request.ServerVariables["SERVER_PORT"];
            if (port == null || port == "80" || port == "443")
                port = "";
            else
                port = ":" + port;

            string protocol = System.Web.HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"];
            if (protocol == null || protocol == "0")
                protocol = "http://";
            else
                protocol = "https://";

            string sOut = protocol + System.Web.HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + port + System.Web.HttpContext.Current.Request.ApplicationPath;

            if (sOut.EndsWith("/"))
            {
                sOut = sOut.Substring(0, sOut.Length - 1);
            }

            return sOut;

        }

        ...etc., your other properities

}



Get this property in any cshtml page as below in layout.cshtml page or in any global page

@model your.namespace.LocalMVCModel

<script type="text/javascript">
   currentDomain = '@(Model.CurrentDomain)';

</script>

or simply

<script type="text/javascript">
   currentDomain = '@(Url.Content("~"))';

</script>


 Notes:
- Razor syntax @ cannot be accessed in *.js files, so add script in cshtml page itself preferrably in layout page or some global page.
- Single quote required for razor syntax to consider as string
- Variable currentDomain in javascript can be declared anywhere in JS files and accessed here.


1 comment: