当前位置: 动力学知识库 > 问答 > 编程问答 >

asp.net mvc - Active Select option in Razor

问题描述:

I am working on a mobile version of my website. I have the option Action working however when I select, for example "About" it will take me to the correct page but the navigation bar goes back to the "Home" option. How do I go about doing this? thanks in advance

<select class="navbar-nav" style="width:250px" onchange='location.href = this.value'>

<option value="@Url.Action("Index", "Home")">Home</option>

<option value="@Url.Action("About", "Home")">About</option>

<option value="@Url.Action("Products", "Home")">Products</option>

<option value="@Url.Action("Services", "Home")">Services</option>

<option value="@Url.Action("Contact", "Home")">Contact</option>

</select>

网友答案:
    <option selected="@ViewBag.Home" value="@Url.Action("Index", "Home")">Home</option>
    <option selected="@ViewBag.About" value="@Url.Action("About", "Home")">About</option>
    <option selected="@ViewBag.Products" value="@Url.Action("Products", "Home")">Products</option>
    <option selected="@ViewBag.Services" value="@Url.Action("Services", "Home")">Services</option>
    <option selected="@ViewBag.Contact" value="@Url.Action("Contact", "Home")">Contact</option>

and in your Home.cshtml

@{
    ViewBag.Home = true;
}

and the other pages.

网友答案:

You can do it like this :

@{
    Dictionary<string, string> menu = new Dictionary<string, string>();
    menu.Add("Home", @Url.Action("Index", "Home"));
    menu.Add("About", @Url.Action("About", "Home"));
    menu.Add("Products", @Url.Action("Products", "Home"));
    menu.Add("Services", @Url.Action("Services", "Home"));
    menu.Add("Contact", @Url.Action("Contact", "Home"));    

}
<select class="navbar-nav" style="width:250px" onchange='location.href = this.value'>
   @foreach (var m in menu)
   {
     <option value="@m.Value" @(m.Value == Request.Url.AbsoluteUri ? "selected='selected' " : "")>@m.Key</option>  
   } 
</select>
分享给朋友:
您可能感兴趣的文章:
随机阅读: