Get @Html.DropDownList selected value

16,519

Use strongly typed helpers that bind to your model. If your model contains property CustomCarsList

public class CustomCar
{
  ....
  public int CustomCarsList { get; set; } // assumes `CustomCarID` is typeof int
}

then in the view

@model CustomCar
@using (Html.BeginForm()) {
  ....
  @Html.DropDownListFor(m => m.CustomCarsList, (SelectList)ViewBag.CustomCars)
  <button type="submit">Submit</button>                      
}

and in the controller

public ActionResult UnregisteredSection(string dropdownlistReturnValue) // dont know what dropdownlistReturnValue is doing?
{
  CustomCar model = new CustomCar();
  model.CustomCarsList = // some value
  ViewBag.CustomCars = new SelectList(db.Garage.SqlQuery(selectString), "CustomCarID", "CustomCarDescription"); // selectedInt is not required
  return View(model);
}

[HttpPost]
public ActionResult UnregisteredSection(CustomCar model)
{
  // model.CustomCarsList contains the value of the selected option
}

then if the value of CustomCarsList matches the value of one of your option values (defined by CustomCarID) then that is the option that will be selected, otherwise the first option will be selected. On post back the value of CustomCarsList will be the value of the option selected by the user.

Share:
16,519

Related videos on Youtube

E_N_T_E_R
Author by

E_N_T_E_R

Updated on June 04, 2022

Comments

  • E_N_T_E_R
    E_N_T_E_R almost 2 years

    I´m trying to get SELECTED value from @Html.DropDownList in ASP .NET MVC 5 (C#). I´ve got this DropDownList in View:

    @Html.DropDownList("CustomCarsList", ViewBag.CustomCars as SelectList)
    

    ViewBag.CustomCars is defined in UnregisteredSectionController in public ActionResult

    UnregisteredSection() method as:

    string selectString = "Select * from CustomCars where OwnerId ='" + User.Identity.GetUserId() +"'";
    
    ViewBag.CustomCars = new SelectList(db.Garage.SqlQuery(selectString), "CustomCarID", "CustomCarDescription", selectedInt);
    

    I don´t want to use JavaScript for that and I have tried lot of tutorials but without success. Selected value have to be passed as param for other already created function.

    EDIT

    This is DrowDownList code in UnregisteredSection view:

    @using (Html.BeginForm(FormMethod.Post)) {
    @Html.DropDownList("selectedCustomCar", (SelectList)ViewBag.CustomCars);
    
    <button type="submit">Submit</button>                      
    }
    

    This is code in UnregisteredSectionController:

    public ActionResult UnregisteredSection(string dropdownlistReturnValue)
        {
            string selectString = "Select * from CustomCars where OwnerId ='" + User.Identity.GetUserId() +"'";
    
            //To pass list of Departments from the controller, store them in ViewBag
            ViewBag.CustomCars = new SelectList(db.Garage.SqlQuery(selectString), "CustomCarID", "CustomCarDescription", selectedInt);
    
            //toTest
            System.Diagnostics.Debug.WriteLine(dropdownlistReturnValue);
    
            return View();
        }
    

    And finally this is model code:

    public class CustomCar
    {
        public int CustomCarID { get; set; }
        public string Name { get; set; }
        public int TankCapacity { get; set; }
        public string FuelType { get; set; }
        public int Maxoutput { get; set; }
        public decimal FuelOutside { get; set; }
        public decimal FuelTown { get; set; }
        public decimal FuelMix { get; set; }
        public string OwnerId { get; set; }
    
        public int selectedCustomCar { get; set; } //new
    
        public string CustomCarDescription
        {
            get
            {
                return string.Format("{0}, {1}kW, {2}", Name, Maxoutput, FuelType);
            }
        }
    }
    public class DefaultConnection : DbContext
    {
        public DbSet<CustomCar> Garage { get; set; }
    }
    
    • markpsmith
      markpsmith over 9 years
      Are you saying the select value isn't being POSTed when you submit the form?
    • E_N_T_E_R
      E_N_T_E_R over 9 years
      @markpsmith I tried to use Html.BeginForm and it POSTED value to UnregisteredSection() method correctly but it also refreshed View(page) and this is not good to me.
    • markpsmith
      markpsmith over 9 years
      You need to POST to a different action method, call it 'Update' for example.
    • E_N_T_E_R
      E_N_T_E_R over 9 years
      @markpsmith Thanks for your answer. And what should that action method 'Update' return (what type of return value)?
    • markpsmith
      markpsmith over 9 years
      The 'Update' action method handles the database update, so once that's done, you would return to your original Index page or wherever you wanted the user to go, using RedirectToAction("Index")
    • markpsmith
      markpsmith over 9 years
      I think you're getting in a bit of a mess. It looks like you want to display list of users, then display a list cars belonging to a selected user, then display the details of a selected car. Is that right?
  • E_N_T_E_R
    E_N_T_E_R over 9 years
    Thanks for response. Could you explain me shortly, how does 'm => CustomCarsList' works - like whad does 'm'mean, or '=>'? Because when I´m using it, ist not working (Cannot convert lambda expression to type string because its not delegate type)
  • Admin
    Admin over 9 years
    I'll update my answer in a few minutes (sorry it should be m => m.CustomCarsList - stupid typo)
  • E_N_T_E_R
    E_N_T_E_R over 9 years
    After changing that, same warning is there. I´ve got @model FuelCalc.Models.CustomCar on a first row of view with DropDownList. Is it correct or there should be something else? Or its necessary to have some other reference on 'm'?
  • Admin
    Admin over 9 years
    @E_N_T_E_R, See update (@Html.DropDownListFor(m => m.CustomCarsList, (SelectList)ViewBag.CustomCars)). But what is dropdownlistReturnValue in the GET method?
  • E_N_T_E_R
    E_N_T_E_R over 9 years
    dropdownlistReturnValue was used for receiving selected value when clicked on Submit button. As I said, I tried lot of solutions for my problem an this variable is just some 'garbage' from one of it. I've already updated my code by your solution - everything is fine appart of 'm => m.CustomCarsList, (SelectList)ViewBag.CustomCars' - still same error from Visual Studio.
  • Admin
    Admin over 9 years
    Are you sure you are using DropDownListFor (not DropDownList).
  • E_N_T_E_R
    E_N_T_E_R over 9 years
    Oh, sorry. My mistake. But now after choosing some item in DropDL and click on Submit button, Visual Studio stop with this error: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'selectedCustomCar'. selectCustomCar is same like CustomCarList (is defined in CustomCar model as you can see in my UPDATED question above). Thank you for your answers, I´m so helpless with this.
  • Admin
    Admin over 9 years
    That means that ViewBag.CustomCars is null. Is this happening when you first load the page or only when you post back and then return the view? If so then you need to reassign the ViewBag.CustomCars property before you return the view.
  • E_N_T_E_R
    E_N_T_E_R over 9 years
    When I first load the page everything seems to work properly but. All cars are in DropDownList but then when I choose some car a click on submit, it fails with this error.
  • Admin
    Admin over 9 years
    Yes, please read my last comment - you need to reassign the ViewBag property again if you return the view (as you did in the GET method) And put a breakpoint on the first line of the POST method and step through the code so you can see that the value of selectedCustomCar is correctly bound
  • E_N_T_E_R
    E_N_T_E_R over 9 years
    Ok, I did that. The POST method is working correctly but there is no value in received parameter. I tried to use this: System.Diagnostics.Debug.WriteLine("Here"+model.Name); but only 'Here' was on Debug, no Name of selected model from drop down list.
  • Admin
    Admin over 9 years
    What do you mean model.Name? Did you create a control for the Name property - @Html.TextBoxFor(m => m.Name)? The only code I included was for the CustomCarsList property (which I think you have now renamed to selectedCustomCar but not sure)