2017-08-27 45 views
0

我一直在摸索我的頭幾個小時試圖解決這個問題。我已經嘗試了大部分關於這個問題的代碼,並沒有成功地獲得正確的指導和答案,以處理@ html.dropdown。我有一個從控制器ViewBag獲取價值的下拉菜單。ASP.net MVC @ html.dropdown不返回選定的值

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

並在我看來我寫了。

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

我試過@ html.dropdownlist而不是listfor。

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

我想從下拉列表或列表中使用jQuery獲取選定的值。我已經嘗試了大多數答案,它們是:

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

並且它們都不起作用。有人可以幫助我嗎?

回答

1

理想情況下,您不需要將DropDownList的ID重命名爲hello

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

相反,你需要使用#通過ID來獲得一個元素中的jQuery。 How do I get the text value of a selected option?

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

如果腳本里面View.cshtml,你甚至可以使用強類型的HTML輔助Html.IdFor

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

如果你想選擇的值,你可以只使用.val()

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

要引用的元素通過它的id,你需要使用哈希(#)選擇,就像這樣:

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