.NET Core< select>具有默认值?

编程入门 行业动态 更新时间:2024-10-24 20:12:16
本文介绍了.NET Core< select>具有默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的目标是生成具有特定选择值的< 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&lt; select&gt;具有默认值?

本文发布于:2023-11-17 03:17:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1608622.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:默认值   amp   Core   NET   gt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!