【问题标题】:creating a dropdownlist in mvc 5 in visual studio 2013在 Visual Studio 2013 的 mvc 5 中创建下拉列表
【发布时间】:2015-10-22 07:53:13
【问题描述】:

您好,我在 mvc5 中创建下拉列表时遇到问题, 这就是我的模型中的内容:

public string CountryCode { get; set; }
public LocationChecker()
{
    PopulateCountryCodes();
}

public IEnumerable<SelectListItem> CountryCodes { get; set; }

private void PopulateCountryCodes()
{
    CountryCodes = new List<SelectListItem>();
    CountryCodes.Add (new SelectListItem {Value = "1", Text =“UK”});

    CountryCodes.Add (new SelectListItem {Value = "2", Text =“GB”});

    CountryCodes.Add (new SelectListItem {Value = "3", Text =“IRL”});
}

这是我的观点:

<h4>Countries</h4>
  add a drop down list

  @Html.DropDownListFor(m => m.CountryCode, Model.CountryCodes)
</div>

CountryCodes.Add 中的 ADD 是红色的,无法解决,而且我在 UK、GB 和 IRL 之前还有“预期表达式”错误。

任何帮助将不胜感激。这是我第一次使用 mvc5 顺便说一句。

谢谢

导航

【问题讨论】:

    标签: c# asp.net-mvc drop-down-menu asp.net-mvc-5 selectlistitem


    【解决方案1】:

    我可以看到一个问题,引号字符不太适合 Text 属性。

    你有这个:

        CountryCodes.Add (new SelectListItem {Value = "1", Text =“UK”});
    
        CountryCodes.Add (new SelectListItem {Value = "2", Text =“GB”});
    
        CountryCodes.Add (new SelectListItem {Value = "3", Text =“IRL”});
    

    试试这个:

        CountryCodes.Add (new SelectListItem {Value = "1", Text ="UK"});
    
        CountryCodes.Add (new SelectListItem {Value = "2", Text ="GB"});
    
        CountryCodes.Add (new SelectListItem {Value = "3", Text ="IRL"});
    

    【讨论】:

    • 两种场景调用new SelectListItem()new SelectListItem{}无参构造函数没有区别
    • 感谢您的快速回复,我也改了 CountryCodes.Add(new SelectListItem() {Value = "England"});它已删除表达式错误,但 ADD 仍为红色。请对此有任何帮助。
    【解决方案2】:

    在后端,构建一个SelectList

    countryCodes = new List<SelectListItem>();
    countryCodes.Add(new SelectListItem() { Text = "theText", Value = "TheValue" });
    

    分配给您的视图模型(this 在构造函数中,因此是“this”)

    this.CountryCodes = new SelectList(countryCodes, "Value", "Text", "Please Select");
    

    而在前端(CountryCode 是一个 int,是你的视图模型的一个成员)

    @Html.DropDownListFor(model => model.CountryCode, this.Model.CountryCodes, new { placeholder = "Please select a Country Code", @class = "form-control", name = "CountryCodeSelected" })
    

    【讨论】:

      猜你喜欢
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 2015-02-18
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多