1

我想创建一个显示国家列表的简单下拉框。它的数据来自数据库,并使用实体框架数据上下文进行访问。用户应在发回数据之前选择一个国家/地区。(简单的验证检查)。

我已经创建了视图模型并且还编写了一些代码,但是我不确定我的设计并且我还需要帮助来完成代码。我已经做了一些搜索,但我找不到这样做的简单方法。我仍然从上下文中获取数据,因为我仍然不确定如何使用存储库。目前,我只希望基本的下拉菜单能够正常工作而不会太高级。请帮忙。感谢 更新 的视图模型 - 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");
            }
        }

谢谢

4

2 回答 2

1

在您的控制器中执行此操作:

var model = new Country {
    // assuming that the country with "id" exists
    CountryId = ctx.Countries.Get(id).Id
};
model.Countries = 
    from q in ctx.Countries
    select new SelectListItem { 
        Text = q.Id, 
        Value = q.Name
    };
return view("countries", model);

在您的模型中执行此操作

@model Models.Country

@Html.DropDownListFor(model => model.CountryId, model.Countries)
于 2013-04-12T10:43:13.073 回答
0

try this:

[Required(ErrorMessage = "Please select a Country")]
public string CountryCode{ get; set; }

public IEnumerable<SelectListItem> CountryList
{
    get
    {
        return Country
            .GetAllCountry()
            .Select(Country=> new SelectListItem 
            { 
                Text = Country.Value, 
                Value = Country.Value 
            })
            .ToList();
    }
}

and then you could add a corresponding validation error message:

@Html.DropDownListFor(model => model.CountryCode, Model.CountryList, "select")
@Html.ValidationMessageFor(model => model.CountryCode)
于 2013-04-12T10:47:08.107 回答