需要帮助来完成下面的代码,在MVC中使用<selectlistitem>进行简单的下拉列表</selectlistitem>

时间:2013-04-12 10:28:16

标签: c# asp.net-mvc razor asp.net-mvc-4

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

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

由于

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

试试这个:

[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();
    }
}

然后您可以添加相应的验证错误消息:

@Html.DropDownListFor(model => model.CountryCode, Model.CountryList, "select")
@Html.ValidationMessageFor(model => model.CountryCode)