MVC DropDownList lagging

前端 未结 1 515
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-24 05:30

I am posting the id of a dropdownlist back to the index (index2 view). but is lagging behind. After a second time pressing Select it shows me the correct list.

http://

1条回答
  •  悲哀的现实
    2021-01-24 06:23

    You have added a route value using new { @id = Request.Form["SelectedContinent"] } in your BeginForm() method.

    Assuming the initial value is 0, then it generates action = "/CountriesWorld/Index2/0". Lets assume you select the option with value="1" and you now post the form. The id attribute is bound to 0 and you filter the Countries based on .Where(e => e.Continent == 0) - no where have you ever used the value of the selected option which is bound to a non-existent property named SelectedContinent.

    Now you return the view and the forms action attribute is now action = "/CountriesWorld/Index2/1" (because Request.Form["SelectedContinent"] is 1). If you select the option with value="2", the same thing occurs - you ignore the value of the selected option and the filter the Countries based on .Where(e => e.Continent == 1) because the id parameter is 1.

    Always bind to a model, which in your case will be

    public class CountriesVM
    {
        public int? SelectedContinent { get; set }
        public IEnumerable ContinentsList { get; set; }
        public IEnumerable Countries { get; set; }
    }
    

    and in the view, strongly bind to your model (note the FormMethod.Get and the 3rd parameter in DropDownListFor())

    @model CountriesVM
    @using (Html.BeginForm("Index", "CountriesWorld", FormMethod.Get))
    {
        @Html.DropDownListFor(m => m.SelectedContinent, Model.ContinentsList, "All")
        
    }
    
        ....
        @foreach(var country in Model.Countries)
        {
            ....
        }
     

    and you need only one method

    public ActionResult Index(int? selectedContinent)
    {
        var countries = _context.Countries.OrderBy(e => e.Country);
        if (selectedContinent.HasValue)
        {
            countries = countries.Where(e => e.Continent == selectedContinent.Value);
        }
        continentsList = _context.Continents.Select(x => new SelectListItem
        {
            Value = x.Continent.ToString(),
            Text = x.Continentomschrijving
        });
        var model = new CountriesVM
        {
            SelectedContinent = selectedContinent,
            ContinentsList = continentsList,
            Countries = countries
        };
        return View(model);
    }
    

    Note you might also want to consider caching the Continents to avoid repeated database calls assuming they do not change often (and invalidate the cache if their values are updated)

    0 讨论(0)
提交回复
热议问题