如何在布局中从JS渲染局部视图

时间:2017-04-03 23:45:38

标签: javascript asp.net-mvc razor

尝试使用JS来渲染基于URL的局部视图...这几乎可以工作,但是我不能在PathRoot Var中使用Razor语法,所以我尝试了它,但它没有做到渲染...任何想法将不胜感激。



<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>
&#13;
&#13;
&#13;

它将剃刀语法写入头部,但页面已经呈现。我可以在更新磁头后渲染剃刀语法吗?

&#13;
&#13;
<head>
@Html.Partial("~/Views/shared/FloodlightTags/first.cshtml");
</head>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

除了斯蒂芬的答案,你可以这样做:

@{
    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将获取网站url,然后它将检查匹配的http://www.website.com/天气,如果是,它将呈现first.cshtml否则它将检查第二个条件。

答案 1 :(得分:0)

使用您的代码时可以这样做

 <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>