2017-08-27 44 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();