Hi @Alick Wang
each select's selected value can be get from the model,then how to set the selected item to be related one?
```<option value='2'>ms</option>``` ```<option value='3'>gg</option> ``` ```<option value='4'>fb</option> ``` ```<option value='5'>wc</option> ``` ```</select>```
To set the selected option based on the page model, you can use asp-for
attribute.
Refer to the following sample:
@model TestMVC.Models.SelectedViewModel
@{
ViewData["Title"] = "SelectedIndex";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Selecte>dIndex</h1>
<h4>SelectedViewModel</h4>
<hr /
<div class="row">
<div class="col-md-4">
<form asp-action="SelectedIndex">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<select id='unitID' name='UnitName' asp-for="SelectedValue" asp-items="Model.SelectOptions">
</select>
</div>
<div class="form-group">
<select id='unitID' name='UnitName' asp-for="SelectedValue">
<option value='2'>ms</option>
<option value='3'>gg</option>
<option value='4'>fb</option>
<option value='5'>wc</option>
</select>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
The page model SelectedViewModel as below:
{
public class SelectedViewModel
{
public int SelectedValue { get; set; }
public List<SelectListItem> SelectOptions { get; set; }
}
In the controller, we can return the page model with the selected value.
public IActionResult SelectedIndex()
{
var select = new SelectedViewModel()
{
SelectedValue=3,
SelectOptions = new List<SelectListItem>()
{
new SelectListItem(){ Value="2", Text="ms"},
new SelectListItem(){ Value="3", Text="gg"},
new SelectListItem(){ Value="4", Text="fb"},
new SelectListItem(){ Value="5", Text="wc"}
}
};
return View(select);
}
The result as below: check the second drop-down list. the first drop-down list uses the asp-items
to bind the select options.
Note: By using the above code, since we add the name attribute in the select element, when submit the form, we have to get the selected value via the UnitName.
So, in the post action method, you can add a action parameter and named UnitName
.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion