Rasmus Rajje Josefsson Rasmus Rajje Josefsson - 3 months ago 13
jQuery Question

Getting the Id from a dropdown list with razor syntax in mvc 5

I'm able to reterive the text field, but using the razor syntax of getting the attribute doesn't work, i'm getting undefined when trying to get it from the data-genre-id="@item.Id".

$(".dropdown-menu li")
.on('click',
function() {
$(".dropdown-toggle").text($(this).text());
var id = $(this).attr("data-genre-id");
console.log(id);
});


..


<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Dropdown
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">

@foreach (var item in Model.Genres)
{
<li><a data-genre-id="@item.Id">@item.Name</a></li>
}
<li role="separator" class="divider"></li>
<li><a href="#">Separated link</a></li>

</ul>
</div>

Answer

data-genre-id attribute belong to a element no li , so when you click on li must find a Element and get data-genre-id attribute.

Change your Code Like this :

$(document).ready(function(){

    $(".dropdown-menu li").on('click',function() {

        $(".dropdown-toggle").text($(this).text());

        var id = $(this).find("a").attr("data-genre-id");

        console.log(id);
    })
})

Final code :

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <div class="dropdown">
        <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
            Dropdown
            <span class="caret"></span>
        </button>
        <ul class="dropdown-menu" aria-labelledby="dropdownMenu1">

            @foreach (var item in Model.Genres)
            {
            <li><a data-genre-id="@item.Id">@item.Name</a></li>
            }         
            <li role="separator" class="divider"></li>
            <li><a href="#">Separated link</a></li>

        </ul>
    </div>
   
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
$(document).ready(function(){
    
    $(".dropdown-menu li").on('click',function() {
        
        $(".dropdown-toggle").text($(this).text());
        
        var id = $(this).find("a").attr("data-genre-id");
        
        console.log(id);
    })
})
    </script>
</body>
</html>

Comments