Trying to use JS to render a partial view based on the URL... This is almost working but I can't use Razor syntax in the PathRoot Var so I tried escaping it but then it doesn't render... Any Ideas would be greatly appreciated.
<head> <script> var SiteUrl = window.location.hostname; var FloodlightPathRoot = '@@Html.Partial("~/Views/shared/FloodlightTags/' ; var FloodlightEnd = '");'; switch (SiteUrl) { case "www.website.com": var FloodlightFilePath = "first.cshtml"; break; case "www.website2.com": var FloodlightFilePath = "second.cshtml"; break; } var FloodFull = (FloodlightPathRoot + FloodlightFilePath + FloodlightEnd); $('head').append(FloodFull); </script> </head>
It writes the razor syntax to the head but the page has already rendered. Can I render the razor syntax after the head is updated?
<head> @Html.Partial("~/Views/shared/FloodlightTags/first.cshtml"); </head>
in addition to Stephen's answer you can do it like this:
@{
var url = new Uri(new Uri(this.Context.Request.Url.GetLeftPart(UriPartial.Authority)), Url.Content("~/")).ToString();
if (url == "http://www.website.com/")
{
@Html.Partial("~/Views/shared/FloodlightTags/first.cshtml");
}
else if (url == "http://www.website2.com/")
{
@Html.Partial("~/Views/shared/FloodlightTags/second.cshtml");
}
}
var url
will get the site url
and then it will check weather it matches http://www.website.com/
if so it will render first.cshtml
else it will check the second condition.
While using your code it can done this way
<head>
<script>
@{
string path = Request.RequestUri.PathAndQuery;
if (path.Contains("www.website.com"))
{
@Html.Partial("~/Views/shared/FloodlightTags/first.cshtml");
}
else if (path.Contains("www.website.com"))
{
@Html.Partial("~/Views/shared/FloodlightTags/second.cshtml");
}
}
</script>
</head>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.