【问题标题】:how to set the value in DropDownListFor?如何在 DropDownListFor 中设置值?
【发布时间】:2019-07-17 13:41:29
【问题描述】:

有 CreatePage 浏览量:

 <select name='Fields[0].TypeFields' onchange='addElement(this);'>
     <option>Type of field</option>
     <option value='1'>One of the list</option>
     <option value='2'>several of the list</option>
     <option value='3'>Drop-down list</option>
     <option value='4'>Text-string</option>
     <option value='5'>Text-paragraph</option>
  </select>
<input type="submit" value="Save">

可使用 onchange='addElement(this) 扩展表单,因此 name='Fields[0].TypeFields'。 按下按钮将值发送到数据库。如果选择“列表之一”,则发送 value='1'。 但是当我进入表单编辑页面时,该值设置为默认的“字段类型”。

 @Html.DropDownListFor(model => model.Fields[i].TypeFields, new SelectListItem[]
  {
    new SelectListItem(){ Text="Type of field", Disabled = false},
    new SelectListItem(){ Text="One of the list", Value = "1"},
    new SelectListItem(){ Text="Several of the list", Value = "2"},
    new SelectListItem(){ Text="Drop-down lis", Value = "3"},
    new SelectListItem(){ Text="Text-string", Value = "4"},
    new SelectListItem(){ Text="Text-paragraph", Value = "5"}},
    new { @onchange = "addElement(this);" })

如果选择了“1”,我需要选择“列表之一”。也许我选择了错误的方式。

 public class Field
        {
            public int Id { get; set; }
            public string TypeFields { get; set; }

            //other properties

            public int? NewFormId { get; set; }
            public virtual NewForm NewForm { get; set; }
        }
  public class NewForm
        {
            public int Id { get; set; }

             //other properties

            public virtual List<Field> Fields { get; set; }
        }

【问题讨论】:

  • 我认为您需要使用ViewBag 并为第二个选项设置Selected = true 设置,然后将ViewBag 值传递给下拉列表帮助器,而不是在视图页面内使用SelectListItem 数组。

标签: c# asp.net asp.net-mvc-4 razor


【解决方案1】:

正如你所说,这是一条艰难的道路。如果你有 100 个字段,你不能像这样添加它们 :) 填充视图包并作为数据源提供。你可以参考这里:https://www.c-sharpcorner.com/article/different-ways-bind-the-value-to-razor-dropdownlist-in-aspnet-mvc5/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-18
    • 1970-01-01
    • 2017-06-02
    相关资源
    最近更新 更多