KendoUI Datasource Component - javascript

I wrote two functions,assume that one of them get us list of all notifications and one of them get new notification, i wrote a script which call first method and get list of all notifications in Json format, and write another script which call second method every 8 second, and get us new notifications in Json format too. i show these notifacations in a KendoUI Datasource. so i have two datasource for just one KendoUI Datasource component, i want to add two data source in one datasource, is there any way to do this?
EDIT: This is my code
<script id="template" type="text/x-kendo-template">
<tr>
<td>#= ID #</td>
<td>#= TITLE #</td>
<td>#= DESC #</td>
</tr>
</script>
My first script which get us list of all notification :
var datas = function () {
var objects = [];
$.ajax({
type: "POST",
url: "./WebForm1.aspx/GetNoti",
data: {},
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function (response) {
for (var i = 0; i < response.d.length; i++) {
objects.push({ 'ID': response.d[i].ID, 'TITLE': response.d[i].TITLE, 'DESC': response.d[i].DESC });
}
},
});
return objects;
};
var dataSource = new kendo.data.DataSource({
data: datas(),
change: function () {
$("#movies tbody").html(kendo.render(template, this.view()));
}
});
dataSource.read();
and this is my seccond script which call method that give us new notifications every 8 sec:
$("#go").click(function () {
setInterval(
function () { test2();}, 8000);
});
var p = function () {
var objects = [];
$.ajax({
type: "POST",
url: "./WebForm1.aspx/GetUnCheckNotification",
data: {},
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function (response) {
for (var i = 0; i < response.d.length; i++) {
objects.push({ 'ID': response.d[i].ID, 'TITLE': response.d[i].TITLE, 'DESC': response.d[i].DESC });
}
},
});
return objects;
};
function test2() {
var dataSource2 = new kendo.data.DataSource({
data: p(),
change: function () {
$("#movies tbody").html(kendo.render(template, this.view()));
}
});
dataSource2.read();
}
Now i want some thing like this :
dataSource = dataSource + dataSource2
dataSource.read();
Is there anyway?

JSON format cab be a nested structure. Define a view model and then use it.
public class Report
{
public int Id {set; get;}
public string Title {set; get;}
public string Desc {set; get;}
}
public class MyReportViewModel
{
public List<Report> NewNotifications {set;get;}
public List<Report> AllNotifications {set;get;}
}
Then serialize this new MyReportViewModel { ... } using Json.NET library (server side).
On the client side, you can use the returned JSON format as usual.

Never tried anything like this. But when I was looking for your answer, I found this link at Telerik Forums.
Two Data Sources, One Grid
This might help.! :)

Related

How to pass local storage item to MVC controller

I am trying to pass an array of strings from my local storage (key value) to MVC controller. Here's my code:
In cshtml View file:
<script>
function getFavouriteBooks() {
var ids = JSON.parse(localStorage.getItem("bookIds"));
// returns: ["1", "2", "3"]
$.ajax({
type: "POST",
traditional: true,
url: '#Url.Action("Favourites", "Home")',
data: { ids: ids },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
alert(result.Result);
}
}});
}
</script>
<button onClick="getFavouriteBooks()">Display Favourites</button>
My controller:
public async Task < ViewResult > Favourites(string ids) {
// code that fetches book data from API
if (data != null)
{
var bookList = JsonConvert.DeserializeObject < Book[] > (data);
foreach(var book in bookList) {
var matches = new List < bookList > ();
if (bookList.All(book => ids.Contains(book.Id))) {
matches.Add(book);
}
return View("Index", matches.ToArray());
}
}
return View("Index");
}
The controller action gets called successfully on the button click but the ids parameter is always null even though it isn't when in the console. Where am I going wrong?
from what you have described, I strongly feel this is the problem of expecting asynchronous function to behave synchronously,
await foreach(var book in bookList) {
var matches = new List < bookList > ();
if (bookList.All(book => ids.Contains(book.Id))) {
matches.Add(book);
}
return View("Index", matches.ToArray());
}
Try adding await before you call foreach loop. or better use for in loop
Thanks for your help everyone, the solution was actually to change this part of the ajax call to:
data: { ids: localStorage.getItem('videoIds') },
This code was tested in Visual Studio.
You have to create a viewModel:
public class IdsViewModel
{
public string[] Ids { get; set; }
}
Replace this:
var ids = JSON.parse(localStorage.getItem("bookIds"));
// returns: ["1", "2", "3"]
// or you can use
var ids = localStorage.getItem('videoIds'); //it still will be working
$.ajax({
type: "POST",
traditional: true,
url: '#Url.Action("Favourites", "Home")',
data: { ids: ids },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
with this
var ids= JSON.parse(localStorage.getItem("bookIds"));
$.ajax({
type: "POST",
url: '/Home/Favourites',
data: { ids:ids },
success: function (result) {
....
and the action
public async Task <ActionResult> Favourites(IdsViewModel viewModel) {
var ids=viewModel.Ids;
.....

Passing A Single Objects Into An MVC Controller Method Using jQuery Ajax

I'm trying to post a single object data to an MVC Controler using JQuery, Below are my codes.
//declare of type Object of GroupData
var GroupData = {};
//pass each data into the object
GroupData.groupName = $('#groupName').val();
GroupData.narration = $('#narration').val();
GroupData.investmentCode = $('#investmentCode').val();
GroupData.isNew = isNewItem;
//send to server
$.ajax({
url: "/Admin/SaveContributionInvestGroup",
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify({ GroupData: JSON.stringify(GroupData) }),
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
Below is my controller.
[HttpPost]
public JsonResult SaveContributionInvestGroup(ContributionInvestmentGroup GroupData)
{
ClsResponse response = new ClsResponse();
ClsContributionInvestmentGroup clsClsContributionInvestmentGroup = new ClsContributionInvestmentGroup();
var userID = (int)Session["userID"];
var sessionID = (Session["sessionID"]).ToString();
if (contributionGroupData != null)
{
//get the data from the cient that was passed
ContributionInvestmentGroup objData = new ContributionInvestmentGroup()
{
contributionInvestmentGroupID = 0,
groupName = GroupData.groupName,
narration = GroupData.narration,
investmentCode = GroupData.investmentCode,
isNew = GroupData.isNew
};
response = clsClsContributionInvestmentGroup.initiateNewContributionInvestmentGroup(sessionID, objData);
}
else
{
response.IsException = true;
response.IsSucess = false;
response.Message = "A system exception occurred kindly contact your Administrator.";
}
return Json(new
{
response.IsSucess,
response.Message
});
}
The issue is, the data is not been posted to the controller, the controller receives a null object.
Kindly assist, would really appreciate your effort, thanks.
Try Like this:
//send to server
$.ajax({
type: "POST",
url: "/Admin/SaveContributionInvestGroup",
dataType: "json",
data: GroupData,
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
in your controller your dont have custom binding to bind JSON to your model thats why you get null in you parameter.
instead just post it as query, try simply changes your ajax option like so:
{
...
contentType: "application/x-www-form-urlencoded", //default:
...,
data: $.param(GroupData),
...
}
and perhaps property names are case sensitive so you will need to change your javascript model's name

Pass array from client side to service side c#

I am calling a javascript function on button click using onclientclick with below function.
function addValues() {
debugger;
var arrValue = [];
var hdnValue = document.getElementById("hdn").value;
var strValue = hdnValue.split(',');
for (var i = 0; i < strValue.length; i++) {
var ddlValue = document.getElementById(strValue[i]).value;
arrValue.push(ddlValue);
}
}
arrValue array will have all the required values and how can I move this array values to server side for further process.
Update 1:
HTML:
function addValues() {
debugger;
var arrddlValue = [];
var hdnddlValue = document.getElementById("hdnDDL").value;
var strddlValue = hdnddlValue.split(',');
for (var i = 0; i < strddlValue.length; i++) {
var ddlValue = document.getElementById(strddlValue[i]).value;
arrddlValue.push(ddlValue);
}
}
$.ajax({
url: '',
data: { ddlArray: arrddlValue },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
},
error: function (x, e) {
}
});
Code:
protected void btnSort_Click(object sender, EventArgs e)
{
try
{
if (Request["ddlArray[]"] != null)
{
string[] arrValues = Array.ConvertAll(Request["ddlArray[]"].ToString().Split(','), s => (s));
}
}
}
If your framework is ASP.Net you can pass it by $.ajax, I am passing array like:
$.ajax({
url: '',
data: { AbArray: arrValue },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
},
error: function (x, e) {
}
});
and get it in Back-end like:
if (request["AbArray[]"] != null)
{
int[] arrValues = Array.ConvertAll(request["AbArray[]"].ToString().Split(','), s => int.Parse(s));
}
suppose array is int.
the above sample is using Generic-Handler.
if you want to use webmethod do something like:
[WebMethod(EnableSession = true)]
public static void PassArray(List<int> arr)
{
}
and Ajax would be like:
function addValues() {
debugger;
var arrddlValue = [];
var hdnddlValue = document.getElementById("hdnDDL").value;
var strddlValue = hdnddlValue.split(',');
for (var i = 0; i < strddlValue.length; i++) {
var ddlValue = document.getElementById(strddlValue[i]).value;
arrddlValue.push(ddlValue);
}
var jsonVal = JSON.stringify({ arr: arrValue });
$.ajax({
url: 'YourPage.aspx/PassArray',
data: jsonVal,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
},
error: function (x, e) {
}
});
}
Change Ajax Url as your PassArray address which mean YourPage.aspx should be change to page name which have PassArray in it's code-behind.
For more info Read This.
If you are using Asp.net WebForm Application,
Approach 1 : you can store your array value in a hidden input control and retrieve the saved data in your c# coding.
Approach 2 : define web method in your server side c# code and pass this javascript array value as ajax call.
link for Approach 1 : https://www.aspsnippets.com/Articles/Pass-JavaScript-variable-value-to-Server-Side-Code-Behind-in-ASPNet-using-C-and-VBNet.aspx
link for Approach 2 : https://www.aspsnippets.com/Articles/Send-and-receive-JavaScript-Array-to-Web-Service-Web-Method-using-ASP.Net-AJAX.aspx
I would "stringify" the array by imploding it with a special char unlikely to appear in my values (for example: §), and then with the help of jQuery.ajax() function, I will send it to the backend (ASP.NET MVC) action method:
$.ajax({
url : 'http://a-domain.com/MyController/MyAction',
type : 'POST'
data : 'data=' + myStringifiedArray;
});
My backend would be something like this (in MyController class):
[HttpPost]
public ActionResult MyAction(string data)
{
string[] arrValue = data.Split('§');
...
}
UPDATE
For ASP.NET forms, the ajax request would be:
$.ajax({
url : 'http://a-domain.com/MyPage.aspx/MyMethod',
type : 'POST'
data : 'data=' + myStringifiedArray;
});
And the backend would be something like this:
[System.Web.Services.WebMethod]
public static void MyMethod(string data)
{
string[] arrValue = data.Split('§');
...
}
You will find a more precise explanation here: https://www.aspsnippets.com/Articles/Call-ASPNet-Page-Method-using-jQuery-AJAX-Example.aspx

passing an array of int to MVC controller using ajax javascript

What am I doing wrong here?
I can successfully pass 4 bool params to a controller. Now I want to pass an array of int to my controller but it doesn't work - I've left my working code in the example(commented out) so you can see I'm not changing that much - I think I'm missing something simple (it is 17:44 afterall!!!). I can see the array is populated using the alert(rolesChecked); statement:
var rolesChecked = [];
$('[type="checkbox"].role-checkbox').each(function () {
if (this.checked)
{
rolesChecked.push($(this).val());
}
});
alert(rolesChecked);
//var administrator = $('#cbAdministrator').is(":checked");
//var manager = $('#cbManager').is(":checked");
//var technician = $('#cbTechnician').is(":checked");
//var transcriber = $('#cbTranscriber').is(":checked");
if (rolesChecked.count > 0){//administrator || manager || technician || transcriber) {
$.ajax({
url: '#Url.Action("GetFutureHolidays", "Employee")',
type: 'GET',
dataType: 'json',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: {
roleIdXXXs: rolesChecked
//includeAdministrator: administrator,
//includeManager: manager,
//includeTechnician: technician,
//includeTranscriber: transcriber
},
success: function (data) {
//do something...
}
});
}
Controller Action:
public string GetFutureHolidays(List<int> roleIdXXXs)//bool includeAdministrator, bool includeManager, bool includeTechnician, bool includeTranscriber)
{
//do something
}
with the old code, the controller action would be hit... with the array, it never gets hit... What am I missing here...
also, I think List<int> roleIdXXXs should be fine, but I also tried List<string>, int[] and string[] in case it isn't!!!
You need to add the traditional: true ajax option to post back an array to the collection
$.ajax({
url: '#Url.Action("GetFutureHolidays", "Employee")',
type: 'GET',
dataType: 'json',
cache: false,
data: { roleIdXXXs: rolesChecked },
traditional: true, // add this
success: function (data) {
}
});
Refer also the answer to this question for more detail on what the options does and the form data it generates.
In your if statement, instead of rolesChecked.count, use rolesChecked.length
You can't submit a list like this from Ajax, the quickest fix in the process you are using is to use serialization-desalinization process, you can send it as
roleIdXXXs: JSON.stringify(rolesChecked)
on Action:
public ActionResult GetFutureHolidays(string rolesChecked)
{
var test = new JavaScriptSerializer().Deserialize<List<int>>(rolesChecked);
}
You should use JSON.stringify() on you AJAX call lice this:
data: {
roleIdXXXs: JSON.stringify(rolesChecked)
//includeAdministrator: administrator,
//includeManager: manager,
//includeTechnician: technician,
//includeTranscriber: transcriber
}

Convert JQuery ajax GET to POST

I have this jquery ajax get method on an Index razor in my application:
$.ajax({
url: "#Url.Action("SubmitProjectForPreapproval", "api/Project")",
type: "GET",
cache: false,
data: { projectId: "#ViewContext.RouteData.Values["ProjectId"]" }
}).done(function (data) {
var count = 0;
$.each(data, function (index, value) {
$("#ulMessages").append("<li>" + value + "</li>");
count++;
});
// Assume validation errors if more than 1 message
if (count > 1) {
$("#btnSubmit").removeAttr("disabled");
}
}).fail(function () {
$("#ulMessages").append("<li>An error occurred. Please try again later</li>");
$("#btnSubmit").removeAttr("disabled");
}).always(function () {
$("#imgAjaxLoader").hide();
});
This calls a method within the api/project controller that returns a list of strings:
[HttpGet]
public List<string> SubmitProjectForPreapproval(int projectId)
{ ... }
What I want to do is convert this to an ajax post method. I've been struggling to do just that for the better part of the day. My question is, what is everything that needs to change in order for this to happen? e.g. - change attribute of the method to [HttpPost], and how do I send it the route value? (int pojectId)
Edit: If I do this it works for some reason:
public List<string> SubmitProjectForPreapproval(/*int projectId*/)
{
int projectId = 3308;
...
}
Not sure why it doesn't find my method if I have the parameter there.
I'm not sure how the #Url stuff formats with your system - but just changing it to something like:
$.ajax({
url: "#Url.Action("SubmitProjectForPreapproval", "api/Project")",
type: "POST",
cache: false,
data: { projectId: "#ViewContext.RouteData.Values["ProjectId"]" }
}).done(function (data) {
If you're bit:
#Url.Action("SubmitProjectForPreapproval
..actually has any ?xxx values in it, you also need to add them into the data: { ... }
The problem was indeed the way I was sending the data to the controller action. I fixed it by doing the following:
Alter the ajax method (make use of JSON.stringify):
var projectIdObject = {
ProjectId: "#ViewContext.RouteData.Values["ProjectId"]",
}
$.ajax({
url: "#Url.Action("SubmitProjectForPreapproval", "api/Project")",
type: "POST",
cache: false,
data: JSON.stringify(projectIdObject),
contentType: 'application/json',
}).done(function (data) { ... }
Add a class to take this stringified value:
public class ProjectIdObject
{
public string ProjectId { get; set; }
}
Alter the controller action method to receive this new object and extract the value I want:
[HttpPost]
public List<string> SubmitProjectForPreapproval(ProjectIdObject projectIdObject)
{
int projectId = int.Parse(projectIdObject.ProjectId);
...
}

Categories