Search code examples
c#asp.netasp.net-mvc

Set selected index of dropdown to zero after form submit in ASP.NET MVC


I am a bit new to ASP.NET MVC. I have created the below dropdown using HTML helpers in ASP.NET MVC 5. When I submit the form I want to set the selected index to zero. Here I am using an option label "--select--". I want to set the selected value to that one ("--select--") after submitting. How do I achieve this?

@Html.DropDownListFor(model => model.TestCategory, new SelectList(@ViewBag.TestCategories, "value", "text"), "-- Select --", new { @class = "form-control input-sm"})

Controller Code

    [HttpGet]
    public ActionResult Index()
    {
        var model = new LaboratoryViewModel { 
            medicaltestlist = new List<MedicalTest>()
        };
        PopTestCategory();
        PopEmptyDropdown();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(LaboratoryViewModel labvm)
    {
        var test = PopMedicalTests().Where(x => x.TestSerial == Convert.ToInt32(labvm.TestCode)).FirstOrDefault();
        if (labvm.medicaltestlist == null)
            labvm.medicaltestlist = new List<MedicalTest>();
        if(!labvm.medicaltestlist.Any(x=> x.TestSerial == test.TestSerial))
            labvm.medicaltestlist.Add(test);
        labvm.TestCategory = "";
        PopTestCategory();
        return View(labvm);
    }

    public void PopTestCategory()
    {
        var categorylist = new List<DropDownItem>
        {
            new DropDownItem{value="Medical",text="Medical"},
            new DropDownItem{value="Animal",text="Animal"},
            new DropDownItem{value="Food",text="Food"},
            new DropDownItem{value="Water",text="Water"}
        };
        ViewBag.TestCategories = categorylist;
    }

    public class DropDownItem
    {
        public int id { get; set; }
        public string value { get; set; }
        public string text { get; set; }
    }

Solution

  • You return the view in you post method so if you selected (say) Animal then that value will be selected when you return the view because the html helpers use the values from ModelState, not the model property. Setting labvm.TestCategory = ""; has no effect. The correct approach is to follow the PRG pattern and redirect to the GET method, however you can make this work by calling ModelState.Clear(); before setting resetting the value of TestCategory although this will clear all ModelState properties and errors and may have other side effects.

    Side note: You DropDownItem class seems unnecessary. MVC already has a SelectListItem class designed to work with dropdownlists, and in any case you can replace all the code in your PopEmptyDropdown() method with

    ViewBag.TestCategories = new SelectList(new List<string>() { "Medical", "Animal", "Food", "Water" });
    

    and in the view

    @Html.DropDownListFor(m => m.TestCategory, (SelectList)@ViewBag.TestCategories, "-- Select --", new { @class = "form-control input-sm"})