开发者

Javascript wont fire in Html.DropdownList helper in MVC2

Can anyone tell me why the javascript won't submit when the button is clicked on the below scenario?

The controller is like so:

public ActionResult TestJavaScrip()
 {
         TestEntit开发者_运维百科ies db = new Models.TestEntities();

         ViewData["SortOptions"] = new SelectList(db.aspnet_Role, "RoleId", "RoleName");

 return View();
 }

The View contains:

<form>
<%= Html.DropDownList("mySelect",(SelectList)ViewData["SortOptions"],"Please Choose a Role...") %> 
<input type="button" onclick="getIndex()" value="Alert index of selected option"/>
</form>     

Javascript in the Site.master head section is as follows:

<script type="text/javascript">
function getIndex() {
    var x = document.getElementById("mySelect");
    alert(x.selectedIndex);
}
</script>

Rendering as follows:

<form>
<select id="mySelect" name="mySelect"><option value="">mySelect</option>
<option value="133d8e56-XXXX-XXXX-XXXX-35ee34e845aa">Administrator</option>
<option value="7c2a6ed5-XXXX-XXXX-XXXX-fecb42bdeebe">Clerk</option>
<option value="54ebe31d-XXXX-XXXX-XXXX-9821df62f5ed">Client</option>
<option value="63e605eb-XXXX-XXXX-XXXX-b007189a41e5">CPA</option>
<option value="fb644c83-XXXX-XXXX-XXXX-5da4b2dc64a0">Executive</option>
<option value="65efa138-XXXX-XXXX-XXXX-098d9195a99d">Master Administrator</option>
<option value="0c863774-XXXX-XXXX-XXXX-6c8d2418ca6b">Part Qualified Accountant</option>
</select>


<input type="button" onclick="getIndex()" value="Alert index of selected option"/>
</form>

Why is it not firing? I hope someone can see a glaring oversight on my part.


Since your using MVC 2 I assume you have access to the JQuery library that comes with it.

Here is some JQuery that will solve your problem, and a jsfiddle so you can see it in action!

You'll find jsfiddle is a life saver for these sorts of things, if you want a straight javascript solution you can pad one out in there too.

<input type="button" id="btn" value="Alert index of selected option"/>

$(document).ready(function(){
    $('#btn').click(function getIndex() { 
    var x = document.getElementById("mySelect"); 
    alert(x.selectedIndex); 
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜