【问题标题】:How to bind Dropdown List in asp.net MVC from Database using Entity Framework [duplicate]如何使用实体框架从数据库绑定asp.net MVC中的下拉列表[重复]
【发布时间】:2018-01-04 19:37:57
【问题描述】:

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

这没有按预期工作,我不明白我哪里出错了。谁能指出我可能在哪里犯了错误?

【问题讨论】:

  • 网上已经有数百个这样的例子了,你不是第一个有这种要求的人。你找不到任何有用的东西吗?
  • 兄弟 我试过但没有得到想要的答案,网上有很多可用的资源,但由于我是初学者,所以我很难理解它们。终于我做到了。

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


【解决方案1】:

在您的视图文件中

@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

【讨论】:

    【解决方案2】:

    试试这个代码

    @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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-08
      • 2013-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多