I have set up a JQGrid On my Asp.net MVC project and everything works EXCEPT adding a new row in my SQL DB. It successfully adds a row to the jQGrid but does not create the new entry into the DB. I put in a breakpoint in the "create" action method and it gets called. Its worth noting that "Edits" of existing entries work flawlessly. I have been at this for a while. A beer goes to the best answer.
Controller:
public class SettingsController : Controller
{
// GET: Settings
public ActionResult Index()
{
return View();
}
// GET: Users
public ActionResult Users()
{
return View();
}
SmartAdminMvcEntities db = new SmartAdminMvcEntities();
public JsonResult GetValues(string sidx, string sord, int page, int rows) //Gets the todo Lists.
{
//System.Diagnostics.Debug.WriteLine("GetValues");
//Debug.WriteLine("GetValues");
Trace.Write("Error Message");
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
var Results = db.AspNetUsers.Select(
a => new
{
a.Id,
a.UserName,
a.Email,
a.LockoutEnabled,
a.AccessFailedCount,
});
int totalRecords = Results.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
if (sord.ToUpper() == "DESC")
{
Results = Results.OrderByDescending(s => s.Id);
Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
}
else
{
Results = Results.OrderBy(s => s.Id);
Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
}
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = Results
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
// TODO:insert a new row to the grid logic here
[HttpPost]
public string Create([Bind(Exclude = "Id")] AspNetUser obj)
{
//System.Diagnostics.Debug.WriteLine("Create");
string msg;
try
{
if (ModelState.IsValid)
{
db.AspNetUsers.Add(obj);
db.SaveChanges();
msg = "Saved Successfully";
}
else
{
msg = "Validation data not successfull";
}
}
catch (Exception ex)
{
msg = "Error occured:" + ex.Message;
}
return msg;
}
public string Edit(AspNetUser obj)
{
System.Diagnostics.Debug.WriteLine("Edit");
string msg;
try
{
if (ModelState.IsValid)
{
db.Entry(obj).State = EntityState.Modified;
db.SaveChanges();
msg = "Edit Successfully";
}
else
{
msg = "Validation data Edit not successfull";
}
}
catch (Exception ex)
{
msg = "Error occured Editing:" + ex.Message;
}
return msg;
}
public string Delete(int Id)
{
AspNetUser list = db.AspNetUsers.Find(Id);
db.AspNetUsers.Remove(list);
db.SaveChanges();
return "Deleted successfully";
}
}
View:
</div>
<!-- end row -->
<!-- widget grid -->
<section id="widget-grid" class="">
<!-- row -->
<div class="row">
<!-- NEW WIDGET START -->
<article class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<table id="jqgrid"></table>
<div id="pjqgrid"></div>
</article>
<!-- WIDGET END -->
</div>
<!-- end row -->
</section>
<!-- end widget grid -->
</div>
<!-- END MAIN CONTENT -->
@section pagespecific {
<script type="text/javascript">
$(document).ready(function () {
pageSetUp();
jQuery("#jqgrid").jqGrid({
url: "/Settings/GetValues",
datatype: "json",
mtype: 'GET',
height: 'auto',
colNames: ['Id', 'UserName', 'Email', 'LockoutEnabled', 'AccessFailedCount'],
colModel: [
{
key: true,
hidden: true,
name: 'Id',
index: 'Id',
editable: true
}, {
key: false,
name: 'UserName',
index: 'UserName',
editable: true
}, {
key: false,
name: 'Email',
index: 'Email',
editable: true
}, {
key: false,
name: 'LockoutEnabled',
index: 'LockoutEnabled',
editable: true
}, {
key: false,
name: 'AccessFailedCount',
index: 'AccessFailedCount',
editable: true
}],
rowNum: 10,
rowList: [10, 20, 30],
pager: '#pjqgrid',
sortname: 'id',
toolbarfilter: true,
viewrecords: true,
sortorder: "asc",
gridComplete: function () {
var ids = jQuery("#jqgrid").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var cl = ids[i];
be = "<button class='btn btn-xs btn-default' data-original-title='Edit Row' onclick=\"jQuery('#jqgrid').editRow('" + cl + "');\"><i class='fa fa-pencil'></i></button>";
se = "<button class='btn btn-xs btn-default' data-original-title='Save Row' onclick=\"jQuery('#jqgrid').saveRow('" + cl + "');\"><i class='fa fa-save'></i></button>";
ca = "<button class='btn btn-xs btn-default' data-original-title='Cancel' onclick=\"jQuery('#jqgrid').restoreRow('" + cl + "');\"><i class='fa fa-times'></i></button>";
//ce = "<button class='btn btn-xs btn-default' onclick=\"jQuery('#jqgrid').restoreRow('"+cl+"');\"><i class='fa fa-times'></i></button>";
//jQuery("#jqgrid").jqGrid('setRowData',ids[i],{act:be+se+ce});
jQuery("#jqgrid").jqGrid('setRowData', ids[i], {
act: be + se + ca
});
}
},
editurl: '/Settings/Edit',
caption: "Users that have access to the site:",
multiselect: true,
autowidth: true
});
// "/Settings/Create" is being called in the controller. I put in a
// break to test it.
jQuery("#jqgrid").jqGrid("navGrid", "#pjqgrid", {/*navGrid options*/ },
{/*navGrid Edit*/ }, { url: '/Settings/Create' }, { url: '/Settings/Delete' });
jQuery("#jqgrid").jqGrid('inlineNav', "#pjqgrid");
/* Add tooltips */
$('.navtable .ui-pg-button').tooltip({
container: 'body'
});
// remove classes
$(".ui-jqgrid").removeClass("ui-widget ui-widget-content");
$(".ui-jqgrid-view").children().removeClass("ui-widget-header ui-state-default");
$(".ui-jqgrid-labels, .ui-search-toolbar").children().removeClass("ui-state-default ui-th-column ui-th-ltr");
$(".ui-jqgrid-pager").removeClass("ui-state-default");
$(".ui-jqgrid").removeClass("ui-widget-content");
// add classes
$(".ui-jqgrid-htable").addClass("table table-bordered table-hover");
$(".ui-jqgrid-btable").addClass("table table-bordered table-striped");
$(".ui-pg-div").removeClass().addClass("btn btn-sm btn-primary");
$(".ui-icon.ui-icon-plus").removeClass().addClass("fa fa-plus");
$(".ui-icon.ui-icon-pencil").removeClass().addClass("fa fa-pencil");
$(".ui-icon.ui-icon-trash").removeClass().addClass("fa fa-trash-o");
$(".ui-icon.ui-icon-search").removeClass().addClass("fa fa-search");
$(".ui-icon.ui-icon-refresh").removeClass().addClass("fa fa-refresh");
$(".ui-icon.ui-icon-disk").removeClass().addClass("fa fa-save").parent(".btn-primary").removeClass("btn-primary").addClass("btn-success");
$(".ui-icon.ui-icon-cancel").removeClass().addClass("fa fa-times").parent(".btn-primary").removeClass("btn-primary").addClass("btn-danger");
$(".ui-icon.ui-icon-seek-prev").wrap("<div class='btn btn-sm btn-default'></div>");
$(".ui-icon.ui-icon-seek-prev").removeClass().addClass("fa fa-backward");
$(".ui-icon.ui-icon-seek-first").wrap("<div class='btn btn-sm btn-default'></div>");
$(".ui-icon.ui-icon-seek-first").removeClass().addClass("fa fa-fast-backward");
$(".ui-icon.ui-icon-seek-next").wrap("<div class='btn btn-sm btn-default'></div>");
$(".ui-icon.ui-icon-seek-next").removeClass().addClass("fa fa-forward");
$(".ui-icon.ui-icon-seek-end").wrap("<div class='btn btn-sm btn-default'></div>");
$(".ui-icon.ui-icon-seek-end").removeClass().addClass("fa fa-fast-forward");
})
$(window).on('resize.jqGrid', function () {
$("#jqgrid").jqGrid('setGridWidth', $("#content").width());
})
</script>
}
I don't see any clear error in the code of Create
action. Probably one need to debug the code to find the reason. There is mostly one thing, which is important for creating the item: the properties of obj
parameter of Create
. If the properties are correct, then jqGrid interface works correct and the origin of your problem could be only on the server side (your C# code and Entity Framework). One thing, which I would suggest you: to replace the line
db.AspNetUsers.Add(obj);
with
db.AspNetUsers.Add(new AspNetUser { UserName = obj.UserName, Email = obj.Email });
Additionally I'd recommend you to upgrade very old version 4.4.4 (almost 5 years), which you use, to the current version (4.15.2) of "free jqGrid". If you use NuGet package, then you should uninstall it and install the package free-jqGrid. After upgrading to free jqGrid you can use many new features. For example, free jqGrid contains native support of Font Awesome 4.x, which will simplify your code. The usage of gridComplete
is unneeded too. I'd recommend you to return all data from the server (from GetValues
) at once and to use loadonce: true, forceClientSorting: true
options. It will simplifies your code. For other new features I recommend you to start here at the beginning, the wiki articles and READMEs to all previously published versions. For example https://jsfiddle.net/OlegKi/su7ebs65/ demonstrate some features of searching.