在asp.core剃刀页面设置所选项目(Set selected items in asp.core

2019-10-30 09:15发布

我使用ASP核心剃刀页。 这是我的Edit.cshtml.cs:

    [BindProperty]
        public List<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem> CCusers { get; set; }

and here I fill CCusers with data:
 CCusers =new List<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem>() {
                 new Microsoft.AspNetCore.Mvc.Rendering.SelectListItem() { Value = "1", Text = "HR", Selected = true },
                 new Microsoft.AspNetCore.Mvc.Rendering.SelectListItem() { Value = "2", Text = "IT", Selected = false },
                 new Microsoft.AspNetCore.Mvc.Rendering.SelectListItem() { Value = "3", Text = "Account", Selected = false },

            };

在剃刀页,我用了两个不同的选择:

    <select asp-for="CCusers" asp-items="@Model.CCusers" id="CCusers" multiple="multiple" class="selectpicker"> </select>

//and this:

    @Html.DropDownList("NewSelect", Model.CCusers, new { @class = "selectpicker", @multiple = "multiple" })

而这两者的结果:

<select id="CCusers" multiple="multiple" class="selectpicker" name="CCusers"> 
<option value="1">HR</option>
<option value="2">IT</option>
<option value="3">Account</option>
</select>          

<select class="selectpicker" id="NewSelect" multiple="multiple" name="NewSelect">
    <option selected="selected" value="1">HR</option>
    <option value="2">IT</option>
    <option value="3">Account</option>
    </select>

而@ Httml.DropDownList做了它的核心选择没有设置选定的项目。 我很想念在第一选择?

Answer 1:

对于选择标记助手 ,你将需要设置asp-for指定的型号proprety名select元素。

对于您的问题,您需要定义新的属性selected CCusers ,而不是结合的CCusersasp-for直接。

您可以参考下面的代码:

    public class EditModel : PageModel
{
    [BindProperty]
    public int[] SelectedCCuserIds { get; set; }
    [BindProperty]
    public List<SelectListItem> CCusers { get; set; }
    public void OnGet()
    {
        SelectedCCuserIds = new int[] { 1, 2 };
        CCusers = new List<SelectListItem>() {
             new SelectListItem() { Value = "1", Text = "HR" },
             new SelectListItem() { Value = "2", Text = "IT" },
             new SelectListItem() { Value = "3", Text = "Account" },

        };
    }
    public IActionResult OnPost()
    {
        var result = SelectedCCuserIds;
        return RedirectToAction("OnGet");
    }
}

视图

@page
@model CoreRazor.Pages.EditModel
@{
ViewData["Title"] = "Edit";
}
<h2>Edit</h2>
<form method="post">
<select asp-for="@Model.SelectedCCuserIds" asp-items="@Model.CCusers" 
      multiple="multiple" class="selectpicker"> </select>    
      @*@Html.DropDownList("NewSelect", Model.CCusers, new { @class = "selectpicker", 
 @multiple = "multiple" })*@
<div class="form-group">
    <input type="submit" value="Save" class="btn btn-default" />
</div>



文章来源: Set selected items in asp.core razor pages