如何在cshtml的选择列表中选择默认值?

时间:2021-03-17 05:36:55

标签: c# drop-down-menu asp.net-core-mvc razor-pages

我在 cshtml 中使用 select2 创建了一个下拉列表,它允许从下拉列表中选择多个数据。

SelectList studentList = new SelectList(Model.CourseStudents.Select(_ => _.Student).OrderBy(_ => _.DisplayName), "Id", "DisplayName", null);

<div>
        <div class="form-group row-5 col-2">
            <label asp-for="AssignmentStudents">Students</label>
            <select data-placeholder="Select specific students. Leave empty for all students" asp-for="AssignmentStudents" id="UserId" name="UserId" asp-items="studentList" multiple class="js-select2">
            </select>
        </div>
    </div>

上面的代码在表单中创建了一个页面,从下拉列表中选择值后,选项中的用户 ID 转到控制器并保存到数据库中,这很好,但是我如何重定向到页面我需要在提交表单时选择的下拉列表中显示名称我该怎么做?

例如:-

在提交表单时,假设我选择了两个名称 A 和 B,其 Id 分别为 1 和 2。在控制器中,提交表单时,1,2 中的值变为 model.AssignmentStudents,但在重定向到表单时使用相同的值,名称不会显示在下拉列表中。我该怎么做?

1 个答案:

答案 0 :(得分:0)

下面是一个演示

public class SelectModel : PageModel
{
    //....
    [BindProperty]
    public int[] AssignmentStudents { get; set; }
    public void OnGet()
    {
        SelectList studentList = new SelectList(Model.CourseStudents.Select(_ => _.Student).OrderBy(_ => _.DisplayName), "Id", "DisplayName", null);

        ViewData["studentList"] = studentList;
    }
    public IActionResult OnPostTest(int[] AssignmentStudents)
    {
      foreach(var i in AssignmentStudents)
        {
            //...do your logic
        }
      SelectList studentList = new SelectList(Model.CourseStudents.Select(_ => _.Student).OrderBy(_ => _.DisplayName), "Id", "DisplayName", null);
       
      ViewData["studentList"] = studentList;

       return Page();
    }

}

页面:

<form method="post" asp-page-handler="Test">
<div>
    <div class="form-group row-5 col-2">
        <label asp-for="AssignmentStudents">Students</label>
        <select data-placeholder="Select specific students. Leave empty for all students" asp-for="AssignmentStudents" id="UserId" asp-items=@ViewBag.studentList multiple class="js-select2">
        </select>
    </div>
</div>
<input type="submit" value="Click" />
</form>
相关问题