首页  >  问答  >  正文

传递参数或查询字符串给_Layout.cshtml中的顶部导航在ASP.NET中的实现方式

<p>在我的控制器中,我有三个参数。(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>而我在我的导航栏中得到了这个...</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>我想传递一个参数semester的值,使得链接看起来像<code>localhost/Class/List?semester=9&semester=1</code>。谢谢!</p> <p>我尝试过ViewBag和asp-route-id,但是失败了。</p>
P粉343408929P粉343408929414 天前475

全部回复(2)我来回复

  • P粉462328904

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

    这可能不起作用,因为你的ActionResult List期望的是一个字符串列表。根据我的经验,一个字符串列表通常需要你通过循环Model -> item.semester来列出视图中的所有值。

    你可以尝试将List<string>更改为单个string

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

    然后将这个附加到“a”标签。假设你在控制器中填充了一个Viewbag.semesterId

    asp-semester="@ViewBag.semesterId"

    回复
    0
  • P粉754473468

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

    你可以尝试将List转换为查询字符串。 操作:

    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>

    结果:

    回复
    0
  • 取消回复