【问题标题】:MVC Core adding Drop Down List to viewMVC Core 添加下拉列表以查看
【发布时间】:2018-01-02 18:20:39
【问题描述】:

我正在尝试在视图中填充下拉列表。我在使用剃刀语法时遇到了问题(我相信——这个框架只用了几天)。我已经看到了多种方法来做到这一点;但是,我有兴趣让它发挥作用,因此我可以从中学习......:)。这是我所拥有的: 我的数据访问类:

public class DropDown{
public List<SelectListItem> Get_State() //State

    {
        using (SqlConnection conSql = new SqlConnection(conStr)) 
        {
            if (conSql.State == ConnectionState.Closed)
            {
                conSql.Open();
            }

            SqlCommand com = new SqlCommand("Select * From Select_State Order by State", conSql);

            SqlDataAdapter da = new SqlDataAdapter(com);

            DataSet ds = new DataSet();

            da.Fill(ds);

            List<SelectListItem> stateList = new List<SelectListItem>();

            foreach (DataRow dr in ds.Tables[0].Rows)

            {
                stateList.Add(new SelectListItem { Text = dr["StateName"].ToString(), Value = dr["State"].ToString() });
            }

            return stateList;
    }
}

我的模特:

    public class DropDownModel
{
    public List<SelectListItem> State { get; set; }
    public List<SelectListItem> extra1{ get; set; }
    public List<SelectListItem> extra2{ get; set; }
    public List<SelectListItem> extra3{ get; set; }
    public List<SelectListItem> extra4{ get; set; }
}

}

我的控制器:

        public IActionResult DropDown() {
                  DropDownModel dropdown = new DropDownModel();
                  dropdown.State = Get_DropDown.Get_State();

        return View(dropdown);
    }//DropDown

如何获得 razor 语法以显示包含状态的下拉列表?

【问题讨论】:

    标签: razor asp.net-core-mvc


    【解决方案1】:

    不确定确切的问题是什么,因为这很简单。在您看来,您只需这样做:

    <select asp-for="SomeProperty" asp-items="@Model.State"></select>
    

    SomeProperty 将是您希望在发布时将所选值绑定到的模型上的属性。或者,您可以使用HtmlHelper 扩展名:

    @Html.DropDownListFor(m => m.SomeProperty, Model.State)
    

    【讨论】:

    • 问题是我不知道我在做什么 - 仍在努力学习它:)。但是,您的回答做到了。不知道发生了什么。我曾经有过类似的东西,但它没有用,但是当我使用你的答案时,它工作得很好......一定有一个我没有看到的拼写/大小写错误。谢谢!!!
    猜你喜欢
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2021-03-12
    • 2018-01-11
    • 1970-01-01
    相关资源
    最近更新 更多