首页 > 解决方案 > ASP.Net MVC 将值传递给没有专用按钮的控制器

问题描述

我正在尝试将一个值从我的 ViewModel 传递给一个 postmethod,该方法从选择列表中获取 2 个过滤器(一个用于类型,一个用于难度)以及正在过滤其课程的成员的 id。成员的 id 必须传递给 HttpPost 方法,以便 filterByDifficulty 方法知道允许成员获得的最大难度。

简而言之: 我的 get 方法创建了一个视图模型。我将视图模型传递给视图,但我不知道如何将视图模型中的某个属性传递给 post 方法,而不向用户显示/创建单独的按钮。

控制器
id 参数是我所坚持的,我试图弄清楚如何通过视图将它传递给这个方法。

[HttpPost]
public IActionResult LessonsForMember(string filter, string filter2, int id)
        {
            Person person = _personRepository.GetBy(id);
            string Difficulty = person.Difficulty.DifficultyString;
                        PersonLessonModel plm = new PersonLessonModel
            {
                Person = person,
                Types = _lessonRepository.GetTypesLimitedByDifficultyAsSelectList(Difficulty),
                Difficulties = _lessonRepository.GetDifficultiesLimitedByDifficultyAsSelectList(Difficulty),
                Lessons = _lessonRepository.GetFilteredLessons(filter, filter2);
            };
            return View(plm);
         }

看法

我试图在这里某个地方获取@Model.Person.PersonId,而不向用户显示它。我想把它放在最底部的Filter按钮中,但这导致了错误

@model Taijitan.Models.ViewModels.PersonLessonModel

<a asp-controller="Lesson" asp-action="Index">Previous</a>
<br />
<form action="/Lesson/LessonsForMember/" method="post">
    <div class="form-inline">
        <select id="Difficulties" name="filter" asp-items="@Model.Difficulties as List<SelectListItem>" class="form-control">
            <option value="">-- All Difficulties --</option>
        </select>

        <select id="Types" name="filter2" asp-items="@Model.Types as List<SelectListItem>" class="form-control">
            <option value="">-- All Types --</option>
        </select>
        //This causes an error
        <button name="id" value="@Model.Person.PersonId" type="submit">Filter</button>
    </div>
</form>

标签: c#asp.net-coreasp.net-core-mvc

解决方案


您可以将PersonId隐藏输入字段添加到表单中,并将其发布到控制器。

因此,您需要将其包含在表单的底部(确保它在表单内):

@Html.HiddenFor(m => m.Person.PersonId)

推荐阅读