While I'm just starting with ASP.NET MVC and jQuery, I cannot even solve a quite simple task...
I am using a strongly-typed view to display a list of products, where every li-element gets a unique id:
<ul id="product-list">
<% foreach (var item in Model.Products)
{ %>
<li <%= "id=\"product_" + item.Id + "\"" %> >
<div class="item">
<%= item.Name %>
</div>
</li>
<% } %>
&开发者_运维百科lt;/ul>
Now I want to attach to the click-event of every single li-element, so that if the user clicks on a div-element, detailed product-informationen should be loaded asynchronously into a details-pane.
I know how I can use jQuery to invoke an action-method ajax-style and also how to display the json-result which contains the product-details, BUT I have no idea, how I could attach the onclick-event to every single div, so that I can use the productId to load the details.
Can someone please give me some tips, how I could solve this problem?
One way is to use the Attribute Starts With selector to select all list items with ID attribute starting with 'product', and String.split to extract the product id from the ID attribute of the clicked LI, e.g.:
$("li[id^=product]").click(function() {
// split the ID at the '_' to get the product ID (demo)
alert(this.id.split('_')[1]);
// loadDetails would contain your ajax method or whatever,
// it takes the product ID as its argument
loadDetails(this.id.split('_')[1]);
});
Example loadDetails()
implementation using $.get
:
function loadDetails(id) {
$.get('products.aspx', {id: id}, function(html) {
$("#productView").html(html);
});
}
Assuming that all of the list elements on the page represent products:
$(function() {
$('li').click( function() {
var id = $(this).attr('id').replace(/product_/,'');
$.ajax({
url: '<%= Url.Action("details","product") %>/' + id,
dataType: 'json',
type: 'get',
success: function(data) {
...show the details...
}
});
});
});
you can use following jquery to bind a click
event to all the divs inside Li. and then make your ajax call.
$('#product-list li>div').bind('click',function(){
// get the current li Id
var currentLiId = $(this).parent().attr('id');
alert(currentLiId);
// make your ajax call here.
});
You can attach a click event handler to each div:
$("#product-list>li div.item").click(function() {...});
Within that function, 'this' will be the div. The parent li has the "id" attribute you're interested in:
$(this).parent().attr("id")
From there, you should be able to get the product id. jQuery supports an AJAX load method, which you can use on the target div:
$("#results").load("/Product/Details/" + myProductId);
精彩评论