如何在 Razor 中添加新的 SelectListItem 下拉列表

How to add new SelectListItem dropdown in Razor

提问人:marcusredbie 提问时间:11/7/2023 最后编辑:Qiang Fumarcusredbie 更新时间:11/8/2023 访问量:70

问:

基于按钮单击添加新的 SelectListItem 下拉选项的最理想方法是什么?

什么是最佳实践?我考虑了以下选项,并想知道它们是否理想。复制预先存在的行并为其分配新 ID 是否是一种有价值的方法?也许是部分观点?

有没有人对最佳实践方法有想法?理想情况下,我希望避免大量使用jQuery,也许只是为了执行基本功能,而是让c#和.net处理更多的工作。

C# asp.net ASP.net-core Razor

评论


答:

0赞 Qiang Fu 11/8/2023 #1

您可能需要逐个绑定选择列表值以发布旧列表。可以尝试以下示例:
Itemlist.cs

    public class Itemlist
    {
        public string Text { get; set; }
        public string Value { get; set; }
    }

索引视图模型.cs

    public class IndexViewModel
    {
        public string Selected { get; set; }
        public List<Itemlist> List1 { get; set; }
    }

家控制器

        public IActionResult Index(IndexViewModel? model)
        {
            if (model.List1 == null)
            {
                model = new IndexViewModel()
                {
                    List1 = new List<Itemlist>()
                        {
                                new Itemlist { Text = "Physics", Value = "Physics" },
                                new Itemlist { Text = "Maths", Value = "Maths" },
                        }
                };
            }
            return View(model);
        }

        public IActionResult AddSelect(IndexViewModel model,string newOption)
        {
            if (!model.List1.Any(x => x.Text == newOption)&&(newOption!=null))
            {
                model.List1.Add(new Itemlist { Text = newOption, Value = newOption });
            }
            return View("Index", model);
        }

索引.cshtml

@model IndexViewModel

<form asp-controller="home">

    <select asp-for="Selected" asp-items="@(new SelectList(Model.List1, "Value", "Text"))"></select>

    new option: <input name="newOption" />


    @for(int i = 0; i < Model.List1.Count; i++)
    {
        <input type="hidden" asp-for="@Model.List1[i].Text" />
        <input type="hidden" asp-for="@Model.List1[i].Value" />
    }     

    <input type="submit" asp-action="AddSelect" value="Add Option"/>   
    <input type="submit" value="Submit Select" />

</form>
    You Select:  @Model.Selected

测试
enter image description here

评论

0赞 marcusredbie 11/11/2023
非常感谢您的帮助 - 非常感谢。但是,我正在尝试在按下按钮时插入一个 Selectlistitem 下拉框,而不是框本身中的项目