Update Kendo Grid based On Search Form Post - asp.net-mvc

I've been doing alot of searching but haven't found a clear answer for this. I have a set up textboxes that and a submit button and a Kendo UI grid. I want to post the data to the grid's datasource so that it will return the results based on the criteria. I am not using the MVC wrappers.
EDIT:
I've gotten closer but I can't seem to get the datasource to send the post data when I click submit. I've debugged and in my $("#fmSearch").submit it is hitting the jquery plugin and I've confirmed that it is converting the form data to JSON properly, but it seems as though it it not sending the updated information to the server so that the Action can read it.
Javascript
var dsGalleryItem = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Content("~/Intranet/GalleryItem/SearchGalleryItems")',
type: "POST",
data: $("#fmSearch").serializeFormToJSON(),
cache: false
}
},
schema: {
model: {
id: "galleryItemID",
fields: {
galleryItemID: {
nullable: true
},
imageName: {},
collectionName: {},
categoryName: {},
lastUpdatedOn: { type: "date" }
}
}
}
});
var gvResults = $("#gvResults").kendoGrid({
autoBind:false,
columns: [{
field: "imageName",
title: "Item Name",
template: "<a href='#Url.Content("~/Intranet/GalleryItem/Details/")#=galleryItemID#'> #=imageName#</a>"
}, {
field: "collectionName",
title: "Collection"
}, {
field: "categoryName",
title: "Category"
}, {
field: "lastUpdatedOn",
title: "Last Updated",
format: "{0:M/d/yyyy}"
}
],
selectable: "row",
change: onRowSelect,
dataSource: dsGalleryItem
});
$("#fmSearch").submit(
function (event) {
event.preventDefault();
dsGalleryItem.read({ data: $("#fmSearch").serializeFormToJSON() });
});
MVC Action
[HttpPost]
public JsonResult SearchGalleryItems(string keyword, int? category, int? collection, DateTime? startDate, DateTime? endDate)
{
var galleryItemList = (from g in db.GalleryItems
//where g.imageName.Contains(keyword)
select new GalleryItemViewModel
{
galleryItemID = g.galleryItemID,
imageName = g.imageName,
collectionName = g.collection.collectionName,
categoryName = g.category.categoryName,
lastUpdatedOn = g.lastUpdatedOn
});
var galleryItemCount = Json(galleryItemList.ToList());
return Json(galleryItemList.ToList()); ;
}
The action is not setup to retrieve different data right now I just need to know how to connect the form to the grid.

Found the problem. I had this:
dsGalleryItem.read({ data: $("#fmSearch").serializeFormToJSON() });
It needed to be this:
dsGalleryItem.read($("#fmSearch").serializeFormToJSON());

Related

Submit multiple tabs within one view ASP.NET MVC

I have an ASP .NET application with multiple tabs on a view, each tab containing several inputs for each course attendee (name, phone number, job title, etc).
I created a jquery function to collect data from views and generate the JSON accordingly:
function getAttendees() {
var sections = [];
$(".divWithInputs").each(function (i, val) {
var tab = $(val).serializeArray();
sections.push(tab);
});
return sections;
}
And the submit function:
$("#checkoutAttendees").click(function () {
var formData = new FormData();
formData.append("Attendees", JSON.stringify(getAttendees()));
$.ajax({
url: "/controllerURL",
type: 'POST',
contentType: "application/json; charset=utf-8",
cache: false,
contentType: false,
processData: false,
data: formData,
success: function (response) {
alert(response);
}
});
});
I have an issue when reading the JSON, because I need an IEnumerable of Attendee objects to populate with this sort of data:
[
[
{
"name":"first-name-attendee-0",
"value":"Jon"
},
{
"name":"last-name-attendee-0",
"value":"Stark"
},
{
"name":"email-attendee-0",
"value":"jon.stark#northwall.com"
},
{
"name":"phone-attendee-0",
"value":"0181042981029840"
},
{
"name":"company-attendee-0",
"value":"Nightwatch"
},
{
"name":"job-title-attendee-0",
"value":"King"
}
],
[
{
"name":"first-name-attendee-1",
"value":"Aria"
},
{
"name":"last-name-attendee-1",
"value":"Stark"
},
{
"name":"email-attendee-1",
"value":"noemail#nodomain.com"
},
{
"name":"phone-attendee-1",
"value":"000000000000000"
},
{
"name":"company-attendee-1",
"value":"No organization"
},
{
"name":"job-title-attendee-1",
"value":"Killer"
}
],
[
{
"name":"first-name-attendee-2",
"value":"Mad"
},
{
"name":"last-name-attendee-2",
"value":"King"
},
{
"name":"email-attendee-2",
"value":"mad.king#yahoo.com"
},
{
"name":"phone-attendee-2",
"value":"019209840921840219"
},
{
"name":"company-attendee-2",
"value":"Kingdom"
},
{
"name":"job-title-attendee-2",
"value":"King"
}
]
]
Any advise on how to properly transform data from JSON into a list of Attendees ?
Thank you.
Solution: in backend I had to create a list of lists of NameValuePair
The Action method looks like this:
[HttpPost]
public ActionResult TrainingBook(FormCollection formCollection)
var viewModel = new TrainingFormViewModel();
var attendeesListJSON = formCollection["Attendees"];
var attendeesJson = JsonConvert.DeserializeObject<List<List<KeyValuePair<string, string>>>>(attendeesListJSON);
List<Attendees> attendees = new List<Attendees>();
foreach (var item in attendeesJson)
{
attendees.Add(new Attendees {
FirstName = item[0].Value,
LastName = item[1].Value,
WorkEmailAddress = item[2].Value,
PhoneNumber = item[3].Value,
Organization = item[4].Value,
JobTitle = item[5].Value
});
}
A key value pair is name and value for an input, the first list of key value pairs is one attendee, the the list of lists, ofc, all the attendees.

DataSourceResult in asp.net core

When i was worked in Asp.net Mvc , for paging data use KendoUi.this code use in Asp.net Mvc Web api
public DataSourceResult Get(HttpRequestMessage requestMessage)
{
var request = JsonConvert.DeserializeObject<DataSourceRequest>(
requestMessage.RequestUri.ParseQueryString().GetKey(0)
);
WebApplicationDbContext db = new WebApplicationDbContext();
var list = db.Product.ToList();
return list.AsQueryable()
.ToDataSourceResult(request.Take, request.Skip, request.Sort, request.Filter);
}
And now working with Asp.net Core when i was use this code , it doesn't work.
in the error list show to me this error
'Uri' does not contain a definition for 'ParseQueryString' and no
extension method 'ParseQueryString' accepting a first argument of type
'Uri' could be found (are you missing a using directive or an assembly
reference?)
How can i use this code in Asp.net Core?
First remove the HttpRequestMessage requestMessage parameter. Then remove the requestMessage.RequestUri.ParseQueryString().GetKey(0) part and replace it with:
var rawQueryString = this.HttpContext.Request.QueryString.ToString();
// PM> Install-Package Microsoft.AspNetCore.WebUtilities
var rawQueryStringKeyValue = QueryHelpers.ParseQuery(rawQueryString).FirstOrDefault();
var dataString = Uri.UnescapeDataString(rawQueryStringKeyValue.Key); // this is your received JSON data from Kendo UI
I'm not sure why you need to deserialize the request. I normally pass request to ToDataSourceResult extension method.
For example,
public JsonResult Get([DataSourceRequest] DataSourceRequest request)
{
var db = new WebApplicationDbContext();
return db.Product.ToDataSourceResult(request);
}
Thank you VahidN
This project has helped me a lot
KendoUI.Core.Samples
Im use this code in Controller
public DataSourceResult GetProducts()
{
var dataString = this.HttpContext.GetJsonDataFromQueryString();
var request = JsonConvert.DeserializeObject<DataSourceRequest>(dataString);
var list = ProductDataSource.LatestProducts;
return list.AsQueryable()
.ToDataSourceResult(request.Take, request.Skip, request.Sort, request.Filter);
}
And use this code in chstml
#{
ViewData["Title"] = "Home Page";
}
<!--Right to left grid-->
<div class="k-rtl">
<div id="report-grid"></div>
</div>
#section Scripts
{
<script type="text/javascript">
$(function () {
var productsDataSource = new kendo.data.DataSource({
transport: {
read: {
url: "#Url.Action("GetProducts", "Sample03")",
dataType: "json",
contentType: 'application/json; charset=utf-8',
type: 'GET'
},
parameterMap: function (options) {
return kendo.stringify(options);
}
},
schema: {
data: "data",
total: "total",
model: {
fields: {
"id": { type: "number" }, //Determine the field for dynamic search
"name": { type: "string" },
"isAvailable": { type: "boolean" },
"price": { type: "number" }
}
}
},
error: function (e) {
alert(e.errorThrown);
},
pageSize: 10,
sort: { field: "id", dir: "desc" },
serverPaging: true,
serverFiltering: true,
serverSorting: true
});
$("#report-grid").kendoGrid({
dataSource: productsDataSource,
autoBind: true,
scrollable: false,
pageable: true,
sortable: true,
filterable: true,
reorderable: true,
columnMenu: true,
columns: [
{ field: "id", title: "RowNumber", width: "130px" },
{ field: "name", title: "ProductName" },
{
field: "isAvailable", title: "Available",
template: '<input type="checkbox" #= isAvailable ? checked="checked" : "" # disabled="disabled" ></input>'
},
{ field: "price", title: "Price", format: "{0:c}" }
]
});
});
</script>
}

Knockout-Kendo dropdownlist Ajax observableArray get selected item name

My application is MVC 5, I use the following Knockout-kendo dropdown list:
<input data-bind="kendoDropDownList: { dataTextField: 'name', dataValueField: 'id', data: foodgroups, value: foodgroup }" />
var ViewModel = function () {
var self = this;
this.foodgroups = ko.observableArray([
{ id: "1", name: "apple" },
{ id: "2", name: "orange" },
{ id: "3", name: "banana" }
]);
var foodgroup =
{
name: self.name,
id: self.id
};
this.foodgroup = ko.observable();
ko.bindingHandlers.kendoDropDownList.options.optionLabel = " - Select -";
this.foodgroup.subscribe(function (newValue) {
newValue = ko.utils.arrayFirst(self.foodgroups(), function (choice) {
return choice.id === newValue;
});
$("#object").html(JSON.stringify(newValue));
alert(newValue.name);
});
};
ko.applyBindings(new ViewModel());
It works great, thanks to this answer Knockout Kendo dropdownlist get text of selected item
However when I changed the observableArray to Ajax:
this.foodgroups = ko.observableArray([]),
$.ajax({
type: "GET",
url: '/Meals/GetFoodGroups',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
self.foodgroups(data);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
Controller - get the table from ms sql server:
public JsonResult GetFoodGroups()
{
var data = db.FoodGroups.Select(c => new
{
id = c.FoodGroupID,
name = c.FoodGroupName
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
I get this error when I alert the item name
Unable to get property 'name' of undefined or null reference
What is the difference between hardcoding the array items from using Ajax.
The 'id' field has string datatype in hard coded array.
The 'id' field has number datatype in ajax array.
.
So, the 'id' field has different datatypes in both arrays. However in-condition you have used === operator so it checks value as well as datatype.
For ajax array value is same but its datatype is different so its not returning result.
Let me know if any concern.

How to initialize the selection for rails-select2 in BackboneForms schema?

The project uses marionette-rails, backbone-on-rails, select2-rails and this port to BackboneForms to provide a multiselect form field. The select options are available to the user. They are retrieved from the collection containing the total list of options:
MyApp.module("Products", function(Products, App, Backbone, Marionette, $, _) {
Products.CustomFormView = Products.CustomView.extend({
initialize: function(options) {
this.model.set("type", "Product");
Products.EntryView.prototype.initialize.apply(this, arguments);
},
schemata: function() {
var products = this.collection.byType("Product");
var productTypes = products.map(function(product){
return {
val: product.id,
label: product.get("name")
};
});
return {
productBasics: {
name: {
type: "Text",
title: "Name",
editorAttrs: {
maxLength: 60,
}
},
type: {
type: 'Select2',
title: "Product type",
options: {
values: productTypes,
value: [3, 5],
initSelection: function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
}
},
editorAttrs: {
'multiple': 'multiple'
}
}
}
};
}
});
});
Do I initialize the value correctly in options.value? How comes initSelection is never called? I copied the function from the documentation - it might be incomplete for my case. None of the products with the IDs 3 and 5 is displayed as the selection.
initSelection is only used when data is loaded asynchronously. My understanding is that there is no way of specifying the selection upon initialization if you are using an array as the data source for a Select2 control.
The best way of initializing the selection is by using setValue after the form is created. Here is a simplified example based on the code in your example.
var ProductForm = Backbone.Form.extend({
schema: {
type: {
type: 'Select2',
title: "Product type",
options: {
values: productTypes,
},
editorAttrs: {
'multiple': 'multiple'
}
}
});
var form = new ProductForm({
model: new Product()
}).render();
form.setValue("type", [3, 5]);
You can use value function (http://ivaynberg.github.io/select2/#documentation) in setValue. I personally recomend you to use this backbonme-forms plugin: https://gist.github.com/powmedia/5161061
There is a thread about custom editors: https://github.com/powmedia/backbone-forms/issues/144

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

Resources