如何使用Entity Framework从数据库绑定asp.net MVC中的Dropdown List

时间:2018-01-04 09:22:25

标签: c# asp.net asp.net-mvc entity-framework asp.net-mvc-4

我是MVC的初学者,尝试使用数据库查找表中的数据将下拉列表绑定到模型。

我的模特:

 public class State
{
    [Required]
    public string StateName { get; set; }
    public int CountryId { get; set; }
    public List<SelectListItem> CountryList { get; set; }

}

在我的控制器中:

[HttpGet]
public ActionResult AddState()
{
    State obj = new State();
    using (MvcWorkEntities context = new MvcWorkEntities())
    {
        obj.CountryList = context.Mst_Country.ToList();
    }
    return View(obj);
}

观点:

@using(Html.BeginForm("AddState","Home",FormMethod.Post))
{ 
<div class="col-md-4">
    <div class="form-group">
        @Html.Label("Select Country")
      @Html.DropDownListFor(m=>m.CountryId,Model.CountryList);
    </div>
</div>
<div class="col-md-4">
    <div class="form-group">
        @Html.Label("Enter State Name")
        @Html.TextBoxFor(m=>m.StateName)
    </div>
</div>
}

这不符合预期,我不明白我哪里错了。谁能指出我可能犯错误的地方?

2 个答案:

答案 0 :(得分:0)

试试此代码

@Html.DropDownListFor(model => model.CountryId , new SelectList(Model.CountryList, "Value", "Text", Model.CountryId))

你也可以使用viewbag,viewdata等

@Html.DropDownListFor(m => m.CountryId, (List<SelectListItem>)ViewBag.CountryList, "Please select")

答案 1 :(得分:0)

在视图文件中

@using(Html.BeginForm("AddState","Home",FormMethod.Post))
{ 
<div class="col-md-4">
    <div class="form-group">
        @Html.Label("Select Country")
      @Html.DropDownListFor(m=>m.CountryId,new SelectList(Model.CountryId,"value","text");
    </div>
</div>
}

链接:https://www.pluralsight.com/guides/microsoft-net/asp-net-mvc-populating-dropdown-lists-in-razor-views-using-the-mvvm-design-pattern-entity-framework-and-ajax