Search code examples
javascriptjqueryasp.net-mvckendo-uikendo-window

Loading data in a Kendo Window with AJAX when a link is clicked


I have an mvc razor page that has several product items listed on it using a razor foreach loop:

@foreach (var product in Model)
{
    <h2>@product.Title</h2>
    <div>product.Description</div>

    <a href="#" class="lnkViewRatings">View Reviews</a>
}

My goal: On the click of any link with the css class 'lnkViewReviews' on it I would like the kendo window to open and display a listing of all of the Reviews for that product using an ajax request. The request will be of type GET and depending on the product where the link was clicked the data param will be the productId.

Here is exactly that I would like (please tell me if there is a better way to do it also):

  1. User clicks View Reviews link by one of the listed products.
  2. A dialog window opens up and pulls in the list of that products reviews in some sort of template that I can specify.

Below is my attempt based on the kendo documentation, but I am having problems. Can you please show me a good way to achieve this?

HTML

<div id="dialog">
    <p>This is static text in my dialog window</p>
</div>

JavaScript

$("#dialog").kendoWindow({
    visible: false
});
var dialog = $("#dialog").data("kendoWindow");

$(".lnkViewReviews").click(function (e) {
    e.preventDefault();

    dialog.refresh({
        url: "/Products/GetReviews",
        data: { productId: $(this).attr('data-product-Id') },
    });

    dialog.open().center();
});

The asp.net MVC controller action method:

public IActionResult GetReviews(int productId)
{
    var prodReviews = _repository.GetProductReviews(productId);

    return Json(prodReviews);
}

Solution

  • From your comments

    how to pass the product id to the click event.

    You can use the new data-* attribute to hold on values in any element.

     @foreach (var product in Model)
        {
            <h2>@product.Title</h2>
            <div>product.Description</div>
    
            <a href="#" data-product-Id="@product.Id" class="lnkViewRatings">View Reviews</a>
        }
    

    And your Jquery can be

    $(".lnkViewReviews").click(function (e) {
        e.preventDefault();
    
        dialog.refresh({
            url: "/Products/GetReviews",
            data: { productId: $(this).attr('data-product-Id') } //You can retrieve product Id from the element itself
        });
    
        dialog.open().center();
    });