Home JQuery passing element by id in razor ASP.Net Core Visual Studio 2017
Reply: 1

JQuery passing element by id in razor ASP.Net Core Visual Studio 2017

Mohamad Mustafa
Mohamad Mustafa Published in 2017-09-12 11:51:51Z

I'm using ASP.Net Core 2.0 on Visual Studio 2017. I'm trying to pass an id element from the _Layout.cshtml in the Shared file to the Index.cshtml which is in the Home file, but my code isn't working.

This is my navigation bar in _Layout.

        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li class="dropdown">
                    <a class="dropdown-toggle" data-toggle="dropdown" href="#">Food and Drinks<span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li><a href="#" class="update" id="restaurant" onclick="update(this)">Restaurant</a></li>
                        <li><a href="#" class="update" id="cafe" onclick="update(this)">Cafe</a></li>
                        <li><a href="#" class="update" id="bakery" onclick="update(this)">Bakery</a></li>

This is my buggy query in Index.cshtml. I'm testing to see if I'm getting the correct id by having alert(type); but it returns the value as undefined each time.

<script type="text/javascript">

$(document).ready(function ($) {
    $(".update").click(function update(e) {
        var type = $(e).attr('id');
            type: 'GET',
            url: '@Url.Action("GetData", "Home")',
            data: { type: type },
            success: function (result) {


Satpal Reply to 2017-09-12 11:59:20Z

Get rid of onclick="update(this)" as you are using unobtrusive event handler

and use current element content this to retrieve attribute value

var type = $(this).attr('id'); //this.id;

Also to persist arbitrary data use custom data-* attributes which can be fetched using .data()

$(".update").click(function(e) {
  var type = $(this).data('id');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="dropdown-menu">
  <li><a href="#" class="update" data-id="restaurant">Restaurant</a></li>
  <li><a href="#" class="update" data-id="cafe">Cafe</a></li>
  <li><a href="#" class="update" data-id="bakery">Bakery</a></li>

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.299952 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO