I'm trying to add a row to a MVC3 WebGrid with pagination enabled using JQuery.
When I add the new row, it's inserted correctly as the last row, but the problem appears when I have more than 1 page in my WebGrid.
The new row that is meant to be inserted at the last row on the last WebGrid page is inserted on the first WebGrid page.
Javascript code:
$("#add-category-dialog").dialog({
resizable: false,
height: 300,
modal: true,
autoOpen: false,
open: function (event, ui) {
var objectid = 0;
$('#add-category-dialog').load("/Categories/CreateEditPartial", { id: objectid });
},
buttons: {
"Save": function () {
var ai = {
categoryID: $(this).data('id'),
Name: $("#Name").val()
};
var json = $.toJSON(ai);
$.ajax({
url: $(this).data('url'),
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('.pretty-table tr:last').after('<tr><td>....</td></tr>');
},
error: function (data) {
var data = data;
alert("Error");
}
});
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
$("#add-category-btn").live("click", function () {
var url = $(this).attr('controller');
$("#add-category-dialog")
.data('url', url)
.dialog('open');
event.stopPropagation();
return true;
});
Controller:
[HttpPost]
pu开发者_开发技巧blic ActionResult Create(Category Category)
{
if (ModelState.IsValid)
{
context.Categories.Add(Category);
context.SaveChanges();
}
return Json(new { Success = Category.CategoryID > 0, Category });
}
View:
var grid = new WebGrid(Model, ajaxUpdateContainerId: "category-grid", canPage: true, rowsPerPage: 30);
@grid.GetHtml(
tableStyle: "pretty-table",
headerStyle: "ui-widget-header",
columns: grid.Columns(
grid.Column("CategoryID", "Id", canSort: true, format: @<b>@item.CategoryID</b>),
grid.Column("Name", "Name", canSort: true, format: @<b>@item.Name</b>)
)
)
With following line you are adding new row as the last row in current page.
$('.pretty-table tr:last').after('<tr><td>....</td></tr>');
WebGrid with paging, displays rows only for particular page. So, the end html (table >tr) generated will be only for that particular page. So, above jQuery line finds the last row in the generated html and inserts row after it. In your case probably the first page. Try to navigate to last page (or any page between first and last) and then add new row and see if this is how it is happening.
The controller code is looking okay and so you should not do anything on ajax call success. Comment above line and test your code. Add new row and navigate to the last page. Your new row should be displayed there.
精彩评论