Reputation: 65
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>
</ul>
</li>
</ul>
</div>
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');
alert(type);
$.ajax({
type: 'GET',
url: '@Url.Action("GetData", "Home")',
data: { type: type },
success: function (result) {
$('#form').html(result);
}
});
});
});
Upvotes: 0
Views: 433
Reputation: 133403
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');
console.log(type);
});
<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>
</ul>
Upvotes: 1