【问题标题】:ASP.Net MVC Passing value to controller without dedicated buttonASP.Net MVC 将值传递给没有专用按钮的控制器
【发布时间】:2020-10-25 06:57:12
【问题描述】:

我正在尝试将一个值从我的 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-core asp.net-core-mvc


    【解决方案1】:

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

    所以您需要在表单底部包含此内容(确保它在表单内):

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

    【讨论】:

      猜你喜欢
      • 2017-06-29
      • 1970-01-01
      • 2020-09-02
      • 2015-05-05
      • 2019-03-24
      • 1970-01-01
      • 2010-09-14
      • 2011-01-01
      相关资源
      最近更新 更多