我想创建一个显示国家列表的简单下拉框。它的数据来自数据库,并使用实体框架数据上下文进行访问。用户应在发回数据之前选择一个国家/地区。(简单的验证检查)。
我已经创建了视图模型并且还编写了一些代码,但是我不确定我的设计并且我还需要帮助来完成代码。我已经做了一些搜索,但我找不到这样做的简单方法。我仍然从上下文中获取数据,因为我仍然不确定如何使用存储库。目前,我只希望基本的下拉菜单能够正常工作而不会太高级。请帮忙。感谢 更新 的视图模型 - Country.cs
public class Country
{ [Required]
public int Id { get; set; }
public IEnumerable<SelectListItem> Countries { get; set; }
}
控制器
Public ActionResult CountriesDropDown()
{
Models.Country countryModel = new Models.Country();
using (ctx)
{
var model = (from q in ctx.Countries
select new SelectListItem
{
Text = q.CountryId,
Value = q.CountryName
}).ToList();
countryModel.Countries = model;
}
return View("Test",countryModel);
}
国家视图
@using (Html.BeginForm("DoSomething", "Test", FormMethod.Post))
{
@Html.DropDownListFor(model => model.Id, Model.Countries, "Please Select")
@Html.ValidationMessageFor(model => model.Id) //The validation part still Not Working. I want the user to select a country before submitting the form. Please help
<input type = submit value="submit" />
}
[HttpPost]
public ActionResult DoSomething(Models.Country Selectedcountry)
//country.Id holds the value of selected drop-down and it works fine
{
if (ModelState.IsValid)
//I need to do server-side validation and return back to client if Selectedcountry.Id is null (just in case, the client-side validation doesn't work)
{
return View();
}
else
{
return View("Test");
}
}
谢谢