.NET Core< select>具有默认值? [英] .NET Core <select> With Default Value?
问题描述
我的目标是生成具有特定选择值的< select>
下拉列表(< option>
)预选,因此最终的 HTML
应该如下所示:
My goal is to generate a <select>
dropdown with a certain select value (<option>
) pre-selected, so the finalized HTML
should look like this:
<select>
<option value = "1">Option1</option>
<option value = "2" selected>Option2</option>
<option value = "3">Option3</option>
</select>
请注意,值为2的选项已选择
属性,表示它将在单击下拉菜单之前显示。我无法(并且正在尝试)使用.NET Core Tag Helpers来实现这一目标。
Note that the option with a value of 2 has a selected
attribute, indicating that it will show before the dropdown is clicked. I cannot (and am trying to) achieve this using .NET Core Tag Helpers.
这是我的模型(我认为您可以放心地忽略细节):
This is my model (I think you can safely ignore the details):
public class ReportViewModel
{
[Display(Name = "Pick a form")]
public IEnumerable<Form> AvailableForms { get; set; }
public Form SelectedForm { get; set; }
public List<ReportData> FormResponses { get; set; }
}
请注意,表格
对象上仅具有 Id
和 Name
属性。
Note that the Form
object there just has Id
and Name
properties on it.
这是我的选择语句:
<label asp-for="SelectedForm.Name" class="form-control-label font-weight-bold"></label>
<select asp-for="SelectedForm.Name"
class="form-control"
onchange ="onFormSelected(this.value)"
asp-items="@(new SelectList(Model.AvailableForms, "Id", "Name"))">
</select>
我没有在 Microsoft指南
或在关于该主题的博客中
推荐答案
基本上,您需要将选择设置为使用 SelectedForm.Id
属性,然后指定要在控制器中选择的表单的值。我不得不稍微更新一下您的代码,但这对我有用-
Basically you need to is set the select to use the SelectedForm.Id
property, then specify the value of the form to be selected in your controller. I had to update your code a little but this works for me -
<label asp-for="SelectedForm" class="form-control-label font-weight-bold"></label>
<select asp-for="SelectedForm.Id"
class="form-control"
onchange ="onFormSelected(this.value)"
asp-items="@(new SelectList(Model.AvailableForms, "Id", "Name"))">
</select>
然后在您的控制器中
var vm = new ReportViewModel()
{
AvailableForms = new List<Form>()
};
var form2 = new Form() { Id = 2, Name = "Bar" };
(vm.AvailableForms as List<Form>).Add(new Form() { Id = 1, Name = "Foo" });
(vm.AvailableForms as List<Form>).Add(form2);
(vm.AvailableForms as List<Form>).Add(new Form() { Id = 3, Name = "Baz" });
vm.SelectedForm = form2;
return View(vm);
这篇关于.NET Core< select>具有默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!