【发布时间】:2020-01-22 11:08:27
【问题描述】:
我有一个非常简单的表单,只有一个下拉控件和一个提交按钮。下拉列表将只包含 1 到 10 个条目。我想要的是能够将填充此下拉列表的列表传递给控制器,以防控制流要求我立即反弹回表单(例如,错误的选择 - 或其他东西......)。理想情况下,我可以重新填充下拉列表,而无需再次查询数据。
这里有一些精简的代码来描述我正在使用的内容。
模型
public class AppointmentViewModel
{
/// <summary>
/// The Id of the appointment request record.
/// </summary>
public string Id { get; set; }
public bool Completed { get; set; }
public bool Declined { get; set; }
/// <summary>
/// The booking confirmation ID
/// </summary>
public string ConfirmationID { get; set; }
/// <summary>
/// Code to indicate why booking failed / success is 100.
/// </summary>
public string BookingCode { get; set; }
/// <summary>
/// Contains all possible purposes for an appointment.
/// </summary>
public List<SelectListItem> Purposes { get; set; }
}
视图 在视图中,我认为我可以简单地将列表存储在隐藏的输入字段中,但字段的“值”最终是列表类型。 html 源代码如下所示:
<input type="hidden" id="Purposes" name="Purposes" value="System.Collections.Generic.List`1[Microsoft.AspNetCore.Mvc.Rendering.SelectListItem]" />
如您所见,我的列表控件中没有项目值。只有它包含的数据类型。
@model AppointmentViewModel
<div class="row mx-auto" style="width:50%">
<div class="col-md-12">
<form method="post" asp-controller="Booking" asp-action="SelectPurpose" asp-route-searchType="1">
<input type="hidden" asp-for="Purposes" />
<div class="form-group">
<label>Go ahead and select a good ol' purpose!</label>
<select asp-for="PurposeId" asp-items="Model.Purposes"></select>
<span asp-validation-for="Purposes" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Check Availability</button>
</form>
</div>
</div>
当将此表单提交给控制器时,模型确实包含所选用途 ID,但用途列表的长度为 0。它不为空,但也不包含任何内容。因此,如果用户被撞回查看下拉列表是空的。
如何将该列表传递给控制器,以便再次将其传回(或可能将其传递给不同的表单)?
【问题讨论】:
-
您实际上可以做的一件事是将列表“缓存”为 javascript 中的 json 对象......并使用 jquery “手工制作”回发,然后您可以根据自己的喜好对对象进行建模...
标签: c# asp.net-core