我正在使用mvc4。如何在DropdownList中绑定CuntryName及其值 的国家
public class Country
{
public int Cnt_Id { get; set; }
public string Cnt_Name { get; set; }
}
这是我的私人班级
public class HybridEmployee
{
public IEnumerable<Country> GetCount { get; set; }
}
控制器
public ActionResult GetCountry()
{
var x = ObjRepo.GetCountry();
hybrid.GetCount = x;
return View(hybrid);
}
Index.cshtml
@model Mvc_Application.Models.HybridEmployee
@using Mvc_Application.Models
@using (Html.BeginForm("SaveEmp", "Home", FormMethod.Post))
{
@Html.DropDownListFor(x=>x.GetCount.FirstOrDefault().Cnt_Id),new SelectList(Model.GetCount,"","");
}
答案 0 :(得分:2)
我们可以有两种方法,如下所示:
ViewBag
。模型文件:
public class State
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public int CountryID { get; set; }
}
在.cs文件中:
ViewBag.Countries = countryService.All().Select(x => new SelectListItem() { Text = x.Name, Value = x.Id.ToString() }).ToList();
在.cshtml文件中:
@Html.DropDownListFor(x => x.CountryID, ViewBag.Countries as IEnumerable<SelectListItem>, "Select Country", new { @class = "form-control" })
模型文件:
public class State
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public int CountryID { get; set; }
public List<SelectListItem> Countries { get; set; }
}
在.cs文件中:
model.Countries = countryService.All().Select(x => new SelectListItem() { Text = x.Name, Value = x.Id.ToString() }).ToList();
在.cshtml文件中:
@Html.DropDownListFor(x => x.CountryID, Model.Countries, "Select Country", new { @class = "form-control" })
答案 1 :(得分:1)
这个表达完全没有意义:
@Html.DropDownListFor(x=>x.GetCount.FirstOrDefault().Cnt_Id),new SelectList(Model.GetCount,"","");
DropDownListFor
helper(Expression<Func<TModel, TProperty>> expression
)的第一个参数不使用LINQ表达式,它是模型绑定表达式 - 您必须使用属性来保存选定的值。下拉列表绑定应该像这样使用:
<强>模型强>
public class Country
{
public int Cnt_Id { get; set; }
public string Cnt_Name { get; set; }
public int SelectedCountry { get; set; } // additional property to get selected value
}
查看强>
@Html.DropDownListFor(x => x.SelectedCountry, new SelectList(Model.GetCount, "Cnt_Id", "Cnt_Value"), null)