0

I have been scratching my head for hours trying to solve this problem. I have tried most codes out there regarding this question and have not succeeded in getting a proper guide and answer to working with @html.dropdown. I have a dropdown which gets value from controller ViewBag.

  public ActionResult FindBirthStones()
        {
            ViewBag.birthstones = new SelectList(dbcontext.GemStoneByMonths, "GemStoneByMonthId", "EnglishZodiac");
            return View();
        }

and in my View I have written.

  @Html.DropDownListFor(m=>m.EnglishZodiac,(SelectList)ViewBag.birthstones, new { @id = "hello" })

I have tried @html.dropdownlist instead of listfor.

 @Html.DropDownList("EnglishZodiac", (SelectList)ViewBag.birthstones, new { @id = "hello" })

and I want to get the selected value from the dropdownlist or listfor using jquery. I have tried most answers which are

 var a=  $("hello").text()
 var a=  $("hello option:selected").text()
var a=  $("hello :selected").text()

and none of them work. Can someone please help me with it.

2 Answers 2

1

To reference an element by it's id you need to use the hash (#) selector, like this:

// To get the text of the selected option
var a = $("#hello option:selected").text();
// To get the value of the selected option
var b = $("#hello").val();
Sign up to request clarification or add additional context in comments.

Comments

1

Ideally, you do not need to rename DropDownList's id to hello.

@Html.DropDownListFor(m => m.EnglishZodiac, (SelectList)ViewBag.birthstones));

Instead, you need to use # to get an element by ID inside jQuery. How do I get the text value of a selected option?

var a = $("#EnglishZodiac option:selected").text();

If the script is inside View.cshtml, you could even use strongly-typed html helper Html.IdFor.

$("#@Html.IdFor(m => m.EnglishZodiac) option:selected").text();

If you want to get the selected value, you could just use .val().

var a = $("#EnglishZodiac").val();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.