You need to create a property to pass the selected datas and bind it to the asp-for
attribute of select tag.
Index.cshtml.cs :
public class IndexModel : PageModel
{
[BindProperty]
public List<int> SelectedTags { get; set; } = new List<int>{ 2, 3 };
[BindProperty]
public List<Tag> Tags { get; set; }
public void OnGet()
{
Tags = new List<Tag> {
new Tag { Id = 1, Value="Mike" },
new Tag { Id = 2, Value="Pete" },
new Tag { Id = 3, Value="Katy" },
new Tag { Id = 4, Value="Carl" } };
}
}
Index.cshtml:
@page
@model WebApplication1_rzaor_page.IndexModel
@{
ViewData["Title"] = "SelectTag";
Layout = "~/Pages/Shared/_Layout.cshtml";
}
<h1>SelectTag</h1>
<label asp-for="Tags">Tags</label>
<select asp-for="SelectedTags"
asp-items="@(new SelectList(Model.Tags, "Id","Value"))">
</select>
Result of this demo
You can refer to this link :Setting Selected Item
Table column width where we store selected value must have the same length with reference table column width from where we retrieve the list value.
If the two columns have different length, the comparison will be false, and no option value will be selected.
Take the following model:
public class SomeModel
{
public ICollection<Tag> Tags { get; set; }
}
public class Tag
{
public int Id { get; set; }
public string Value { get; set; }
}
The model is some kind of object (e.g., a blog entry), that features a list of tags or keywords.
I have a Razor view showing a form to edit a SomeModel
object:
@model SomeModel
@{
// List of available tags is passed by controller
var tags = (List<Tag>)ViewData["Tags"];
}
<label asp-for="Tags">Tags</label>
<select asp-for="Tags"
asp-items="@(new SelectList(tags, nameof(Tag.Id), nameof(Tag.Value)))">
</select>
As expected, this generates a multiple select showing the available tags:
<label for="Tags">Tags</label>
<select class="input-validation-error"
data-val="true" data-val-required="The Tags field is required."
id="Tags" multiple="multiple" name="Tags">
<option value="1">tag1</option>
<option value="2">tag2</option>
</select>
@Model.Tags
correctly contains the currently assigned tags; however, the corresponding options are not marked as selected
.
How do I fix this behavior?
So you mean that I have to create a separate list of tag IDs, instead of passing the
SelectListItem is the default type for binding select tags. When binding different types, you need to specify that the fields correspond to the text and value fields of SelectListItem. You could take a look at this link: