search

Home  >  Q&A  >  body text

How to pass parameters or query strings to the top navigation in _Layout.cshtml in ASP.NET

<p>In my controller I have three parameters. (GET:/Class/List)</p> <pre class="brush:php;toolbar:false;">public class ClassController : Controller { public ActionResult List(string classCode = null, string className = null, List<string> semester = null) { ... } }</pre> <p>And I got this in my navbar...</p> <pre class="brush:php;toolbar:false;"><a class="nav-link text-dark" asp-area="" asp-controller="Class" asp-action ="List">Classes</a></pre> <p>I want to pass a value of parameter semester so that the link looks like <code>localhost/Class/List?semester=9&semester=1</code>. Thanks! </p> <p>I tried ViewBag and asp-route-id, but failed. </p>
P粉343408929P粉343408929513 days ago539

reply all(2)I'll reply

  • P粉462328904

    P粉4623289042023-09-02 09:30:18

    This may not work because your ActionResult List expects a list of strings. In my experience, a list of strings usually requires you to loop through Model -> item.semester to list all the values ​​in the 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. Let's say you populate a Viewbag.semesterId in your controller.

    asp-semester="@ViewBag.semesterId"

    reply
    0
  • P粉754473468

    P粉7544734682023-09-02 09:25:41

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

    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:

    reply
    0
  • Cancelreply