Myar Myar - 5 months ago 31
C# Question

Reloading partial views and Ajax - ASP.NET MVC

I have an interesting problem while reloading partial views with ajax. I have a following setup in the master View:

<div id="items">
@Html.Partial("SubView", Model.Items);

SubView is generally a list of items in a table as follows:

<table class="table table-striped">
@foreach (var item in Model)
@Html.HiddenFor(modelItem => item.Id)
<td>@Html.DisplayFor(modelItem => item.Date)</td>
<td>@Html.DisplayFor(modelItem => item.Time)</td>
@Html.ActionLink("Delete", "Delete", new { itemId= item.Id, page = Model.PageNumber }, new { @class = "deleteItem" })

DeleteItem Action in the controller does basically the following:

public ActionResult DeleteItem(int itemId, int page)
return PartialView("SubView", this.GetPagedList(page));

In the script that I refer in the master View I have the following code:

$(document).ready(function () {
// delete expense
$(".deleteItem").click(function () {

url: this.href,
type: 'delete',
success: function (result) {

return false;

This works fine the first time, but the second time it only loads the partial View -> since the JavaScript code is not being executed...

I am relatively new to that stuff and I am a bit confused what's going on here.
All 3rd party scripts are rendered in the Layout.cshtml


You can't attach a .click() event to a dynamically generated item. You have to structure it this way:

$(document).on('click', '.deleteItem', function() {
    // Deletey stuff here.