用於動態更改ASP中的元素類/id。NET 4.5 MVC

[英]Javascript vs C# for dynamically changing element class/id in ASP.NET 4.5 MVC


I'm new to MVC and still learning, and I would like to know what the convention/best practice is for doing what I described.

我剛接觸MVC,還在學習,我想知道我所描述的習慣/最佳實踐是什么。

I have a menu bar which changes visually based on which page you're on. Currently, I'm doing this with a simple JS .ready() script block at the top of each of my .cshtml view files, and this works just fine. When the page loads it iterates through the menu bar <ul> and changes the <li> id/classes:

我有一個菜單欄,它會根據你所在的頁面進行視覺上的改變。目前,我在我的每個.cshtml視圖文件的頂部使用一個簡單的JS .ready()腳本塊來實現這一點,並且它工作得很好。當頁面加載時,它會遍歷菜單欄

    ,並更改
  • id/類:

  • id /類:
@{ ViewBag.Title = "Test Page"; }
<script>
$(document).ready(function () {
    var listItems = $("#menu-bar li");
    listItems.each(function (li) {
        if ($(this).attr('id') == 'about-link') $(this).addClass('active');
        else $(this).removeClass('active');
    });
});
</script>
<!-- Rest of the .cshtml file... -->

I have a distinct feeling however that this is neither elegant nor optimum. So what would be the best way to accomplish this task specifically for MVC (or in general if that's the case).

我有一種獨特的感覺,這既不雅觀也不適宜。那么,對於MVC來說,完成這個任務的最佳方式是什么呢?

Thank you!

謝謝你!

1 个解决方案

#1


1  

You could use Razor to solve this in your Layout.cshtml file.

你可以用Razor來解決這個問題。cshtml文件。

<ul>
    <li class="@ViewBag.Home">Home</li>
    <li class="@ViewBag.About">About</li>
</ul>

Then at the top of each view, set the right one to active.

然后在每個視圖的頂部,將右視圖設置為活動。

@{
    ViewBag.Home = "active";
}

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/07/22/7254ba62e57e0107b9454d32d9575f2.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com