c# - 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>
解决方案
您可以将PersonId
隐藏输入字段添加到表单中,并将其发布到控制器。
因此,您需要将其包含在表单的底部(确保它在表单内):
@Html.HiddenFor(m => m.Person.PersonId)
推荐阅读
- java - 如果对数据库本身的访问是线程安全的,我们如何确保冗余数据访问应用程序实例在 Java 中安全地工作线程?
- javascript - 如何让 Google Docs 语音输入在开启时保持激活状态?
- flutter - Google 的 OAuth 主页示例
- flutter - Flutter 使网络图像占据全角
- python - Python - Selenium 在提示中有效,但在脚本中无效
- php - Laravel MongoDB 在模型中传递对象
- javascript - 拖动时如何避免意外点击事件?
- ffmpeg - 如果源/目标下降,则使用 ffmpeg 重新流式传输
- powershell - 从注册表项(reg_binary)检查第 13 位(影子设置)?
- javascript - HTML - 样式组件:错误:元素类型无效:需要字符串或类/函数但得到:对象