How to access Customer table's data in nopcommerce - asp.net-mvc

I want to show Customer table's data of nopcommerce in admin page.
i did write a plugin for that and receive data in controller but in view i have a problem and show me error happened message.
here is my controller code:
public class UserDetailsController : BasePluginController
{
private ICustomerService _UserDetail;
public UserDetailsController(ICustomerService UserDetail)
{
_UserDetail = UserDetail;
}
public ActionResult Manage()
{
return View();
}
[HttpPost]
public ActionResult GetUsers(DataSourceRequest userDetail)
{
var details = _UserDetail.GetAllCustomers();
var gridModel = new DataSourceResult
{
Data = details,
Total = details.Count
};
return Json(gridModel);
}
}
And this is my view code:
#{
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
<script>
$(document).ready(function() {
$("#user-details").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("GetUsers", "UserDetails"))",
type: "POST",
dataType: "json",
},
},
schema: {
data: "Data",
total: "Total",
errors: "Errors",
model: {
id: "Id",
}
},
requestEnd: function(e) {
if (e.type == "update") {
this.read();
}
},
error: function(e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
pageable: {
refresh: true,
numeric: false,
previousNext: false,
info:false
},
editable: {
confirmation: true,
mode: "inline"
},
scrollable: false,
columns: [
{
field: "Email",
title: "User Name",
width: 200
},
{
command: [
{
name: "edit",
text: "#T("Admin.Common.Edit")"
}, {
name: "destroy",
text: "#T("Admin.Common.Delete")"
}
],
width: 200
}
]
});
});
</script>
<div id="user-details"></div>
can anybody help me?

Change your GetUsers method on this way:
var details = _UserDetail.GetAllCustomers();
var gridModel = new DataSourceResult
{
Data=details.Select(x=>
{
return new UserDetail()
{
Email= x.Email
};
}),
Total = details.Count(),
};
return Json(gridModel);

Related

Kendo Grid CRUD operations

I'm using a Kendo (for jQuery) Grid in an MVC Core project with Add, Edit, Delete using ajax JSON and SQL Server, but the Update, Destroy and Create actions are not called.
Here is my view:
<div id="grid" class="k-rtl applicationFontLight"></div>
<script>
$(document).ready(function () {
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/Persons/Read",
dataType: "json"
},
update: {
url: "/Persons/Update",
dataType: "json"
},
destroy: {
url: "/Persons/Destroy",
dataType: "json"
},
create: {
url: "/Persons/Create",
dataType: "json"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "id",
fields: {
Id: { editable: false, nullable: true },
firstName: {
type: "string",
validation: {
required: {
message: "Required"
}
}
},
lastName: {
type: "string",
validation: {
required: {
message: "Required"
}
}
},
birthDate: {
type: "string",
validation: {
required: {
message: "Required"
}
}
}
}
}
}
})
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
toolbar: [{ name: "create", text: "New" }],
columns: [
{ field: "firstName", title: "Name", width: "80px" },
{ field: "lastName", title: "Last Name", width: "120px" },
{ field: "birthDate", title: "Birth Date", width: "80px" },
{
command: [{
name: "edit",
text: {
edit: "Edit",
update: "Update",
cancel: "Cancel"
}
}
, {
name: "destroy",
text: "Delete"
}
], width: "200px"
}
],
editable: "inline"
});
});
</script>
And my Controller Code:
public class PersonsController : Controller
{
private readonly DataContext _context;
public PersonsController(DataContext context)
{
_context = context;
}
// GET: Persons
public ActionResult Index()
{
return View();
}
public ActionResult Read()
{
var persons = _context.Persons.ToList();
return Json(persons);
}
public async Task<IActionResult> Create([Bind("Id,FirstName,LastName,BirthDate")] Person person)
{
if (ModelState.IsValid)
{
_context.Add(person);
await _context.SaveChangesAsync();
return Json(person);
}
return View(person);
}
public async Task<IActionResult> Update(int id, [Bind("Id,FirstName,LastName,BirthDate")] Person person)
{
if (id != person.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(person);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!PersonExists(person.Id))
{
return NotFound();
}
else
{
throw;
}
}
return Json(person);
}
return View(person);
}
[ValidateAntiForgeryToken]
public async Task<IActionResult> Destroy(int id)
{
var person = await _context.Persons.FindAsync(id);
_context.Persons.Remove(person);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool PersonExists(int id)
{
return _context.Persons.Any(e => e.Id == id);
}
}
The other actions (besides the Read action) are not called and give me this error in the browser console:
Unexpected character encountered while parsing value: m. Path '', line 0, position 0.
or view Destroy not found...
Replace the following code:
command: [{
name: "edit",
text: {
edit: "Edit",
update: "Update",
cancel: "Cancel"
}
}
, {
name: "destroy",
text: "Delete"
}
], width: "200px"
Try the default column command, then try the toolbar create.
command: ["edit","destroy"], title: " ", width: "200px"

Kendo UI Grid Update button not firing

I am developing a KendoUI Grid with Inline editable option in javascript and can't make Update button to fire click event and post the data to server side update event. Clicking on Update button won't even update the grid on client.
Hope someone can help me point out what I am doing wrong here.
This is not a duplicate to this as I have tired the jfiddle link in the answer and it is not working too.
kendo UI grid update function wont fire
<div id="grid"></div>
#section Scripts{
<script type="text/javascript">
$(function () {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "Home/GetPupilsAsJson",
dataType: 'json'
},
update: {
url: "Home/UpdatePupils",
dataType: 'json',
type: 'POST'
}
},
pageSize: 5,
autoSync: true
});
$('#grid').kendoGrid({
dataSource: dataSource,
editable: "inline",
pageable: true,
columns: [{
field: "Id",
title: "Id",
width: 150,
hidden: true
}, {
field: "Firstname",
title: "Firstname",
width: 150
}, {
field: "Lastname",
title: "Lastname",
width: 150
}, {
field: "DateOfBirth",
title: "DateOfBirth",
width: 150
}, {
field: "Class",
title: "Class",
width: 150
}, {
field: "Year",
title: "Year",
width: 150
},
{
command: ["edit"],
width: 150
}]
});
});
</script>
}
HomeController
public ActionResult GetPupilsAsJson()
{
return Json(GetPupils(), JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Post)]
[HttpPost]
public void UpdatePupils(Pupil p)
{
//never reach here
}
I don't know why but fixed it by putting schema information.
schema: {
model: {
id: "Id",
fields: {
Firstname: { editable: true, validation: { required: true } },
Lastname: { validation: { required: true } },
DateOfBirth: { validation: { required: true } },
Class: { validation: { required: true } },
Year: { validation: { required: true } }
}
}
}
Use #Url.Action("GetPupilsAsJson", "Home")' so no need to pass base url in your update action like this BASEURL+ "Home/GetPupilsAsJson".
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("GetPupilsAsJson", "Home")',
dataType: 'json'
},
update: {
url:'#Url.Action("UpdatePupils", "Home")',
dataType: 'json',
type: 'POST'
}
},
pageSize: 5,
autoSync: true
});
use parameter map to pass model values
<script type="text/javascript">
$(function () {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("GetPupilsAsJson", "Home")',,
dataType: 'json'
},
update: {
url: '#Url.Action("UpdatePupils", "Home")',
dataType: 'json',
type: 'POST'
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
pageSize: 5,
autoSync: true
});
Call Controller with parameterMap
public JsonResult UpdatePupils(string models)
{
return Json(..);
}
Is any of your cell text has HTML tags like < or >, remove them and click on update. The update event will fire.

Kendo UI Upload inside Grid

I am trying to implement Kendo UI Grid with an Kendo Upload inside the grid. While I am using ASP.NET MVC I am not using the Telerik MVC Wrappers. I am attempting to do this without them.
The problem that I am having is that IEnumerable HttpPostedFileBase is null when it posts back to my Action method.
JavaScript:
$(document).ready(function () {
var dsGalleryItemFile = new kendo.data.DataSource({
transport: {
read: "#Url.Content("~/Intranet/GalleryItemFile/ListFiles/")#Model.galleryItemID",
update: {
url: "#Url.Content("~/Intranet/GalleryItemFile/UpdateFile")",
type: "POST"
},
destroy: {
url: "#Url.Content("~/Intranet/GalleryItemFile/DeleteFile")",
type: "POST"
},
create: {
url: "#Url.Content("~/Intranet/GalleryItemFile/CreateFile/")#Model.galleryItemID",
type: "POST"
}
},
// determines if changes will be send to the server individually or as batch
batch: false,
schema: {
model: {
id: "fileID",
fields: {
fileID: {
editable: false,
nullable: true
},
filename: {},
fileType: { defaultValue: {fileTypeID: 1, fileType: "Web JPEG"} },
fileType: {},
width: { type: "number" },
height: { type: "number" },
}
}
}
});
$("#gvGalleryItemFile").kendoGrid({
columns: [{
field: "filename",
title: "Filename"
}, {
field: "filepath",
title: "File Upload",
editor: fileUploadEditor//,
//template: "<img src='#=filepath.filepath#' />"
}, {
field: "fileType",
title: "File Type",
editor: fileTypeDropDownEditor,
template: "#=fileType.fileType#",
}, {
field: "width",
title: "Width"
}, {
field: "height",
title: "Height"
}, {
command: ["edit", "destroy"]
}],
editable: { mode: "inline" },
toolbar: ["create"],
dataSource: dsGalleryItemFile
});
});
function fileTypeDropDownEditor(container, options) {
$('<input required data-text-field="fileType" data-value-field="fileTypeID" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
autoBind: false,
dataSource: {
transport: {
read: "#Url.Content("~/Intranet/FileType/ListFileTypes")"
}
}
});
}
function fileUploadEditor(container, options) {
$('<input type="file" name="fileUpload" id="fileUpload" />')
.appendTo(container)
.kendoUpload({
async: {
saveUrl: "#Url.Content("~/Intranet/GalleryItemFile/UploadFile")"
},
complete: onUploadComplete
});
}
MVC Action:
[HttpPost]
public ActionResult UploadFile(IEnumerable<HttpPostedFileBase> uploadedFiles)
{
if (uploadedFiles != null)
{
foreach (var thisFile in uploadedFiles)
{
string newFileName = Path.GetFileName(thisFile.FileName).Replace(" ", "");
var physicalPath = Path.Combine(Server.MapPath("~/Areas/Gallery/Content/GalleryImages"), newFileName);
thisFile.SaveAs(physicalPath);
}
return Content("");
}
else
{
return Content("Error");
}
}
Try to name the argument parameter in the action method signature the same way as the name attribute of the input that you turn into upload widget.
In your case
public ActionResult UploadFile(IEnumerable<HttpPostedFileBase> fileUpload)

Kendo UI Grid not showing JSON data

I am facing this problem for quite a while now with the problem that I am unable to bind JSON data that my controller action is passing to the kendo UI Grid, there were few JavaScript issues before but now they are gone but still my grid is not showing any results:
In Model:
public object GetResult(string id)
{
var sqlCom = new SqlCommand("SELECT [No],[Desc],[Date],[Height],[Final] FROM [cr_form] WHERE [uId]=#id;", sqlConn);
sqlCom.Parameters.AddWithValue("#id", id);
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
JsonWriter jsonWriter = new JsonTextWriter(sw);
var rcrds = GETSQLRESULTS(sqlCom);
try
{
int i = 0;
if (rcrds != null || rcrds.HasRows)
{
//jsonWriter.WriteStartObject();
while (rcrds.Read())
{
jsonWriter.WriteStartObject(); //Changed
for (int j = 0; j < rcrds.FieldCount; j++)
{
jsonWriter.WritePropertyName(rcrds.GetName(j)); // column name
jsonWriter.WriteValue(rcrds.GetValue(j)); // value in column
}
i++;
jsonWriter.WriteEndObject(); //Changed
}
//jsonWriter.WriteEndObject();
}
}
catch (Exception ex) { }
return jsonWriter;
}
In Controller:
public ActionResult GetRecords()
{
var usrObj = new User();
var jsnRslt = usrObj.GetResult(Session["Id"].ToString());
//Till here jsnRslt contains this string: “{"No":null,"Desc":"asfasfasfasfasfasfasfasfasfasfasfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":null,"No":null,"Desc":"etwetwetwetwet","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"asfasfasfskfjklajsfkjasklfjklasjfklajsfkljaklsfjklasjfkljasfkljlasf","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"askjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfkl","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"safasfasfasfasfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"asfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"asfasfasf","Date":"2013-03-27T00:00:00","Height":2,"Final":0}”
//After Changes in the Model I am getting it in the required Array format:
//{"No":null,"Desc":"asfasfasfasfasfasfasfasfasfasfasfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":null}
//{"No":null,"Desc":"etwetwetwetwet","Date":"2013-03-27T00:00:00","Height":0,"Final":0}
//{"No":null,"Des...
return Json(jsnRslt, JsonRequestBehavior.AllowGet);
}
In View:
<div>
<script type="text/javascript">
$(document).ready(function () {
$("#grid").kendoGrid({
dataSource: {
type: "json",
serverPaging: true,
pageSize: 5,
groupable: true,
selectable: "row",
transport: { read: { url: "Records", dataType: "json"} }
},
height: 400,
scrollable: true,
sortable: true,
filterable: true,
pageable: true,
columns: [
{ field: "No", title: " No" },
{ field: "Desc", title: "Description" },
{ field: "Date", title: "Date" },
{ field: "Height", title: "Height" },
{ field: "Final", title: "Final" }
],
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
}
});
});
</script>
</div>
But after all this all I can see is an empty grid. And no errors in JavaScript console.
Please help
The JSON that you return from the server should be array. You currently it seems that you are returning single objects with multiple fields that are the same.
Here is an example how the JSON should look like:
[{"No":null,"Desc":"asfasfasfasfasfasfasfasfasfasfasfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":null},
{"No":null,"Desc":"etwetwetwetwet","Date":"2013-03-27T00:00:00","Height":0,"Final":0},
{"No":null,"Desc":"asfasfasfskfjklajsfkjasklfjklasjfklajsfkljaklsfjklasjfkljasfkljlasf","Date":"2013-03-27T00:00:00","Height":0,"Final":0}]
I think following code will be useful for you and let me know if you have any problem:
$('#gridName').kendoGrid({
dataSource: {
type: "odata",
transport: {
read: {
contentType: "application/json; charset=utf-8",
type: "POST",
url: 'YourURL'
}
},
pageSize: 10,
type: "json"
},
scrollable: true,
sortable: true,
resizable: true
});
Inside you dataSource set data.
data: #Html.Raw(Json.Encode(Model.RemoteObject)),
RemoteObject is you object containing all data.
First I check your tranport read URL. have you trace the controller if it fires the GetRecords command?
transport:
{
read: {
//if you don't use area then remove it
url: "#Url.Action("GetRecords", new { area = "YourAreaName", controller = "YourControllerName" })",
dataType: "json"
}
}
if it still doesn't fix your problem, then modify your Controller,
public ActionResult GetRecords([DataSourceRequest] DataSourceRequest request)
{
var usrObj = new User();
var jsnRslt = usrObj.GetResult(Session["Id"].ToString());
return Json(jsnRslt.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
here's the link to understand the Kendo's ToDataSourceResult

Unable to bind JSON data to KendoUI Grid

I am facing a certain issue while trying to bind the KendoUi Grid with the Json data from the controller. Things seem fine and my Json object contains data but still grid is not showing any thing:
And I am getting this error in chrome JavaScript console:
GET http://localhost:8084/Records?take=5&skip=0&page=1&pageSize=5 500 (Internal Server Error)
In View:
<div id="grid">
</div>
<div>
<script type="text/javascript">
$(document).ready(function () {
$("#grid").kendoGrid({
dataSource: {
type: "json",
serverPaging: true,
pageSize: 5,
groupable: true,
selectable: "row",
transport: { read: { url: "Records", dataType: "json"} }
},
height: 400,
scrollable: true,
sortable: true,
filterable: true,
pageable: true,
columns: [
{ field: "No", title: "No" },
{ field: "Desc", title: "Description" },
{ field: "priority", title: "Priority" },
{ field: "decision", title: "Decision" }
],
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
}
});
});
</script>
In Controller:
public ActionResult GetRecords()
{
var obj = new User();
var jsnRslt = obj.GetResult(Session["id"].ToString());
//return Json(jsnRslt);
return Json(jsnRslt, JsonRequestBehavior.AllowGet); //Changed as suggested by Dismissile
}
In Model:
public object GetResult(string usrId)
{
…
….
….. try
{
int i = 0;
if (rcrds != null || rcrds.HasRows)
{
jsonWriter.WriteStartObject();
while (rcrds.Read())
{
for (int j = 0; j < rcrds.FieldCount; j++)
{
jsonWriter.WritePropertyName(rcrds.GetName(j));
jsonWriter.WriteValue(rcrds.GetValue(j));
}
i++;
}
jsonWriter.WriteEndObject();
}
}
catch (Exception ex) { }
return jsonWriter;
}
}
Kindly help.
You probably need this in your JSON call:
return Json(jsnRslt, JsonRequestBehavor.AllowGet);
It looks like you are doing a GET call, and by default GET is not allowed on a JSON call.
Try to use the transport attribute within dataSource, something like this:
<script type="text/javascript">
var dataSource = new kendo.data.DataSource({
batch: true,
schema: {
model: {
id: "EmployeeID",
fields: {
EmployeeID: { editable: true, validation: { required: true } },
EmployeeName: { validation: { required: true } }
}
}
},
transport: {
read: {
url: "/Home/GetData",
type: "GET"
},
update: {
url: "/Home/Update",
type: "POST",
contentType: 'application/json'
},
destroy: {
url: "/Home/Destroy",
type: "POST",
contentType: 'application/json'
},
create: {
url: "/Home/Create",
type: "POST",
contentType: 'application/json'
},
pageSize: 1,
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return kendo.stringify(options.models) ;
}
}
}
});
$(document).ready(function () {
$("#grid").kendoGrid({
dataSource: dataSource,
navigatable: true,
pageable: true,
height: 430,
sortable: true,
toolbar: ["create", "save", "cancel"],
columns: [
{ field: "EmployeeID", title: "Employee ID", width: 110 },
{ field: "EmployeeName", title: "Employee Name", width: 110 },
{ command: "destroy", title: "Delete", width: 90 }],
editable: true,
selectable: "multiple row",
groupable: true,
navigatable: true,
filterable: true
});
});
</script>
The controller:
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
var employee = new Employee().GetEmployeeList();
return View(employee);
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetData()
{
var obj = new Employee();
return Json(obj.GetEmployeeList(), JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult Update(List<Employee> model)
{
var obj = new Employee();
//return View();
return Json(obj);
}
[HttpPost]
public JsonResult Create(List<Employee> model)
{
var obj = new Employee();
return Json(obj);
}
public ActionResult Destroy(Employee model)
{
return View();
}
}
Return a html view from index method to hold the grid &
I think you also need to add a datasource request in your ActionMethod Parm
public ActionResult GetResult([DatasourceRequest]request, string usrId)
return Json(jsnRslt.ToDatasourceResult(request), JsonRequestBehavior.AllowGet);
Every kendogrid needs this
Try this
transport: { read: { url: "Records", dataType: "jsonp"} }
try with jsonp instead of json.
You are returning an ActionResult, it should be a JsonResult instead.

Resources