我是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>
}
这不符合预期,我不明白我哪里错了。谁能指出我可能犯错误的地方?
答案 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>
}