Set selected items in asp.core razor pages

2019-06-12 16:51发布

问题:

I'm using ASP Core Razor pages. This my 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 },

            };

In Razor Page, I used two different select:

    <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" })

and this the result of both of them:

<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>

The Core Select didn't set the selected item while the @Httml.DropDownList did it. What I'm missing in the first select?

回答1:

For Select Tag Helper, you will need to set asp-for which specifies the model proprety name for the select element.

For your issue, you need to define new property for selected CCusers instead of binding the CCusers to asp-for directly.

You could refer code below:

Page

    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");
    }
}

View

@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>