如何使用实体框架从数据库绑定asp.net MVC中的下拉列表

问题描述:

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

I am a beginner in MVC and trying to bind drop-down list to a model using data from a database lookup table.

我的模特:

 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>
}

这没有按预期工作,我不明白我要去哪里.有人可以指出我可能在哪里犯错吗?

This isn't working as intended and I don't understand where I am going wrong. Could anyone point out where I might be making a mistake?

尝试此代码

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

您还可以使用viewbag,viewdata等

also you can use viewbag,viewdata and etc

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