Here is my Grid code:
@using Syncfusion.EJ2
<div class="row">
<div class="col control-section">
@Html.EJS().Grid("Grid").DataSource(ds => ds.Url("/Users/Get").InsertUrl("/Users/Insert").RemoveUrl("/Users/Delete").UpdateUrl("Users/Update").Adaptor("WebApiAdaptor")).AllowSorting().Columns(col =>
{
//col.Field("ID").HeaderText("ID").IsPrimaryKey(true).Width("140").ValidationRules(new { required = true, number = true }).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("FirstName").HeaderText("First Name").Width("150").ValidationRules(new { required = true, minLength = 3 }).Add();
col.Field("LastName").HeaderText("Last Name").Width("150").ValidationRules(new { required = true, minLength = 3 }).Add();
col.Field("IsSubscribed").HeaderText("Is Subscribed").EditType("booleanedit").DisplayAsCheckBox(true).Type("boolean").Width("150").Add();
col.Field("LastContactDate").HeaderText("Last Contact Date").EditType("datetimepickeredit").Width("150").Format(new { type = "datetime", format = "M/d/y hh:mm a" }).Add();
}).ActionBegin("actionBegin").AllowPaging().PageSettings(page => page.PageCount(2)).EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Normal); }).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render()
</div>
</div>
<script>
function actionBegin(args) {
var grid = document.getElementById("InlineEditing").ej2_instances[0];
if (args.requestType === 'save') {
args.index = (grid.pageSettings.currentPage * grid.pageSettings.pageSize) - grid.pageSettings.pageSize;
}
}
</script>
Controller:
public class UsersController : Controller
{
private ApplicationDbContext _context = new ApplicationDbContext();
[HttpGet]
public ActionResult Get()
{
var users = _context.Users.Select(m => new UserViewModel
{
ID = m.ID,
FirstName = m.FirstName,
LastName = m.LastName,
LastContactDate = m.LastContactDate,
});
return Json(users.ToList(), JsonRequestBehavior.AllowGet);
}
// POST: Users/Insert
[HttpPost]
public async Task<ActionResult> Insert([Bind(Include = "ID,FirstName,LastName,LastContactDate")] Users user)
{
if (ModelState.IsValid)
{
_context.Users.Add(user);
await _context.SaveChangesAsync();
return new HttpStatusCodeResult(HttpStatusCode.Created);
}
return Json(user, JsonRequestBehavior.AllowGet);
}
// POST: Users/Update/5
[HttpPost]
public async Task<ActionResult> Update([Bind(Include = "ID,ProductID,PlanID,UserGUID,UserID,Password,FirstName,LastName,IsSubscribed,LastContactDate,AuthDigits,EnableTwoFactor,TwoFactorNumber,TwoFactorCountryCode,AuthEmailSent,AuthSMSSent,IsAuthenticated,StatusID,ActiveID,UserFlag,UserField1,UserField2,UserField3")] Users user)
{
if (ModelState.IsValid)
{
_context.Entry(user).State = EntityState.Modified;
await _context.SaveChangesAsync();
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
return Json(user, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public async Task<ActionResult> Delete(long? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Users users = await _context.Users.FindAsync(id);
if (users == null)
{
return HttpNotFound();
}
_context.Users.Remove(users);
await _context.SaveChangesAsync();
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_context.Dispose();
}
base.Dispose(disposing);
}
}
The grid doesn't show any data. All of the examples in the documentation are unfortunately useless. It is such a simple example and it is not in the documentation. Please help!
|
var data = new ej.data.DataManager({
url: '/api/Order',
adaptor: new ej.data.WebApiAdaptor()
});
var grid = new ej.grids.Grid({
dataSource: data,
. . .
height: 273
});
grid.appendTo('#Grid');
|
|
[OrderController]
namespace EJ2Grid.Controllers
{
[Produces("application/json")]
[Route("api/Order")]
public class OrderController : Controller
{
// GET: api/Orders
[HttpGet]
public object Get()
{
var queryString = Request.Query;
int skip = Convert.ToInt32(queryString["$skip"]);
int take = Convert.ToInt32(queryString["$top"]);
var data = OrdersDetails.GetAllRecords().ToList();
return take != 0 ? new { Items = data.Skip(skip).Take(take).ToList(), Count = data.Count() } : new { Items = data, Count = data.Count() };
}
// GET: api/Orders/5
[HttpGet("{id}", Name = "Get")]
public string Get(int id)
{
return "value";
}
// POST: api/Orders
[HttpPost]
// for insert action
public object Post([FromBody]OrdersDetails value)
{
OrdersDetails.GetAllRecords().Insert(0, value);
return value;
}
// PUT: api/Orders/5
[HttpPut]
// for update action
public object Put(int id, [FromBody]OrdersDetails value)
{
var ord = value;
OrdersDetails val = OrdersDetails.GetAllRecords().Where(or => or.OrderID == ord.OrderID).FirstOrDefault();
val.OrderID = ord.OrderID;
val.EmployeeID = ord.EmployeeID;
val.CustomerID = ord.CustomerID;
val.Freight = ord.Freight;
val.OrderDate = ord.OrderDate;
val.ShipCity = ord.ShipCity;
return value;
}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id:int}")]
[Route("Orders/{id:int}")]
// for delete action
public object Delete(int id)
{
OrdersDetails.GetAllRecords().Remove(OrdersDetails.GetAllRecords().Where(or => or.OrderID == id).FirstOrDefault());
return Json(id);
}
public class Data
{
public bool requiresCounts { get; set; }
public int skip { get; set; }
public int take { get; set; }
}
}
} |
Thanks for the reply. Unfortunately, this is a JS-based grid. I need to use the MVC5 grid strictly.
I have followed this and got it working: https://ej2.syncfusion.com/aspnetmvc/documentation/grid/editing/persisting-data-in-server?cs-save-lang=1&cs-lang=razor
I am facing a few more issues:
1) After adding a new row, the topmost row is automatically selected/highlighted (grey background) while the newly added row is at the bottom.
2) To solve the above issue easily, I thought about changing the position of the newly added row in the grid from bottom to top. I have specified .NewRowPosition(Syncfusion.EJ2.Grids.NewRowPosition.Top) in EditSettings of the grid, however, the newly added row still shows at the bottom.
|
@Html.EJS().Grid("Grid").DataSource(dataManger =>
{
dataManger.Url("/api/Orders").CrossDomain(true).Adaptor("WebApiAdaptor");
}).Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("OrderDate").HeaderText("Order Date").Width("150").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
}).AllowPaging().PageSettings(page => page.PageSize(5)).EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Normal); }).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render()
|
I already have it working using the "UrlAdaptor" as mentioned in my previous comment. Kindly answer how to fix these two issues that I am facing after implementing the CRUD operations in Grid: http://www.syncfusion.com/forums/173706/unable-to-do-crud-in-grid-using-asp-net-mvc5-controller?reply=S2J2Cr
|
<script>
var newRowAdded = false;
function selecting(args) { //rowSelecting event of Grid
if (newRowAdded) {
newRowAdded = false;
// Selection is cancelled if it is new row added at bottom case(using global variable)
if (this.editSettings.newRowPosition == 'Bottom') {
args.cancel = true;
// The newly added row index is selected
this.selectRow(this.currentViewData.length - 1);
}
}
}
function begin(args) { //actionBegin event of Grid
if (args.requestType === "save" || args.action === "add") {
newRowAdded = true;
}
}
</script>
|
|
HomeController.cs
public ActionResult Insert(OrdersDetails value)
{
var ord = value;
orddata.Insert(0,ord); //this helps to insert the newly added record in the 1st row position to the list
return Json(value);
}
|