Ren
Ren

Reputation: 1503

Need help to complete the below code for a simple drop-down using <SelectListItem> in MVC

I would like to create a simple drop-down box that displays a list of countries. The data for it comes from the database and is accessed using the entity framework data context. The user should select a country before posting the data back.(simple validation check).

I've created the view model and have also written some code, but I'm not sure about my design and I also need help to complete the code. I've done some search, but I couldn't find a simple way of doing this. I'm still getting the data from context because I am still not sure about how to use repositories. At the moment, I just want the basic drop-down to work without getting too advanced. Please help. Thanks Updated View Model - Country.cs

public class Country
{   [Required]
    public int Id { get; set; }
    public IEnumerable<SelectListItem> Countries { get; set; }
}

Controller

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

Countries View

@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");
            }
        }

Thanks

Upvotes: 1

Views: 179

Answers (2)

Muhammad Omair
Muhammad Omair

Reputation: 797

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)

Upvotes: 0

von v.
von v.

Reputation: 17108

Do this in your controller:

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);

Do this in your model

@model Models.Country

@Html.DropDownListFor(model => model.CountryId, model.Countries)

Upvotes: 1

Related Questions