【问题标题】:Asp.Net MVC Controller keeps adding values to URLAsp.Net MVC 控制器不断向 URL 添加值
【发布时间】:2019-03-07 14:57:34
【问题描述】:

我试图让我的表在索引视图中按某些值过滤,为此我使用 [HttpGet] Index 方法创建 2 个 selectLists(每个过滤器类型一个)。过滤器按钮应该获取每个列表的选定值,并将它们发送到 [HttpPost] 索引方法,该方法过滤表。
问题是我过滤时它不会“重置”url,所以每次我更改过滤器时它都会不断添加到url。

Index Get(这个很好用)

        [HttpGet]
        public IActionResult Index()
        {
            IEnumerable<Lesson> Lessons = _LessonRepository.GetAll();
            ViewData["Types"] = GetTypesAsSelectList();
            ViewData["Difficulties"] = GetDifficultiesAsSelectList();
            return View(Lessons);
        }

Index Post(每次点击我视图中的过滤器按钮时,都会添加/Lesson/Index)

       [HttpPost]
        public IActionResult Index(string filter, string filter2)
        {
            IEnumerable<Les> Lessons = null;
            if (filter == null && filter2 == null)
                Lessons = _LessonRepository.GetAll();
            else if (filter != null && filter2 == null)
            {
                Lessons = _LessonRepository.GetByDifficulty(filter);
            }
            else if (filter == null && filter2 != null)
            {
                Lessons = _LessonRepository.GetByType(filter2);
            }
            else if (filter != null && filter2 != null)
            {
                Lessons = _LessonRepository.GetByType(filter2).Where(l => l.Difficulty == filter);
            }
            ViewData["Types"] = GetTypesAsSelectList();
            ViewData["Difficulties"] = GetDifficultiesAsSelectList();
            return View(Lessons);
        }

查看

<form action="Lesson/Index/" method="post">
    <div class="form-inline">
        <select id="difficulties" name="filter" asp-items="@ViewData["Difficulties"] as List<SelectListItem>" class="form-control">
            <option value="">-- Select difficulty --</option>
        </select>

        <select id="types" name="filter2" asp-items="@(ViewData["Types"] as List<SelectListItem>)" class="form-control">
            <option value="">-- Select type --</option>
        </select>
        <button type="submit">Filter</button>
    </div>
</form>

【问题讨论】:

  • 我不会这样做,我会考虑使用 javascript/jquery 来做。然后您可以清除下拉列表并使用 narkup 填充它。

标签: asp.net post model-view-controller get


【解决方案1】:

这是因为form 标记中的action 属性包含相对URL。请求的结果 url 是 current url + relative url,这就是为什么 Lesson/Index/ 会根据请求附加到当前 url。考虑通过在开头添加/ 来使用绝对网址

<form action="/Lesson/Index/" method="post">

由于您使用的是 ASP.NET Core,您还可以使用 asp-actionasp-controller

<form asp-action="Index" asp-controller="Lesson" method="post">

或者您可以坚持使用相对 url,但您需要考虑生成的 url 是如何构建的。因此,如果您的表单位于 /Lesson/Index 视图上,则可以使用以下操作

<!-- empty action, or you can just remove the attribute completely -->
<form action="" method="post"> 

这会给你current url + relative url = "/Lesson/Index" + "" = "/Lesson/Index"

【讨论】:

    猜你喜欢
    • 2013-07-22
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    • 2015-03-07
    • 1970-01-01
    • 1970-01-01
    • 2012-10-26
    相关资源
    最近更新 更多