简体   繁体   中英

Pass Parameter Or Query String to top nav In _Layout.cshtml In ASP.NET

In my controller, I got three parameters. (GET: /Class/List)

public class ClassController : Controller {
    public ActionResult List(string classCode = null, string className = null, List<string> semester = null) 
    { ... }
}

And I got this in my nav bar...

<a class="nav-link text-dark" asp-area="" asp-controller="Class" asp-action="List">Classes</a>

I would like to pass a value of the parameter semester so that the link will look like localhost/Class/List?semester=9&semester=1 . Thank you!

I have tried ViewBag and asp-route-id but I failed.

It might not work because your ActionResult List is expecting a List of Strings. From my experience, a List of strings usually requires you to loop through the Model -> item.semester to list out all the values in your view.

You can try changing List<string> to a single string .

public ActionResult List(string classCode = null, string className = null, string semester = null) 

Then append this to the "a" tag. Assuming you populate a Viewbag.semesterId in your controller.

asp-semester="@ViewBag.semesterId"

You can try to convert List to query string. action:

public IActionResult A()
        {
            ViewBag.List = new List<string> { "a", "b", "c" };
          
            return View();

        }

A.cshtml:

@{
    var list=ViewBag.List as List<string>;
    var result = "?semester=" +String.Join("&semester=", list);
}
<a class="nav-link text-dark" href="/Class/List@(result)">Classes</a>

result:

在此处输入图像描述

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM