如何使用实体框架从数据库绑定asp.net MVC中的下拉列表 [英] How to bind Dropdown List in asp.net MVC from Database using Entity Framework

查看:143
本文介绍了如何使用实体框架从数据库绑定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")

这篇关于如何使用实体框架从数据库绑定asp.net MVC中的下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆