How to implemnent Paging with kendo pager on demand web api call - kendo-ui

Am calling web api method from view model and getting the 10 records per click. I want paging for kendo template.
this is my code:
// this is the web api method which gets 10 records per each call
function WebApiMethod(parameter)
{
var url = webApiUrl + 'api/{controller}/{methodname}';
var success = function(result)
{
}
CallWebApi(url, 'POST', success, parameter);
}
///this is the ajax call that am calling from webapimethod
function CallWebApi(url, type, successCallBack, data) {
jQuery.support.cors = true;
$.ajax({
cache: false,
type: type,
url: url,
data: JSON.stringify(data),
async: false,
contentType: 'application/json',
success: successCallBack,
error: function (xhr, err) {
}
});
}
///this is the kendo pager in which am biding the datasource
function KendoPager()
{
var pager = $("#pager").kendoPager({
dataSource: ViewModels["NameOfVM"].dataSource,
info: false,
change: function () {
ViewModels["NameOfVM"].pageIndex = pager.page();
}
}).data("kendoPager");
}
//this is the datasource am bind to kendopager
dataSource: new kendo.data.DataSource({
serverPaging:true,
pageSize:10,
})
Thanks in advance.

Related

merge ajaxform with ajax to upload image

I try to create upload photos in my nodejs site.
I used this code to choose file and upload the image:
var fileData = null;
function loadFile() {
var preview = document.querySelector('file');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onloadend = function () {
fileData = file;
}
if (file) {
reader.readAsDataURL(file);
}
}
function uploadFile() {
data = new FormData();
data.append('file', fileData);
$.ajax({
url: "/post_pdf/",
type: "POST",
data: data,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function(data) {
document.getElementById("result").innerHTML = 'Result: Upload successful';
},
error: function(e) {
document.getElementById("result").innerHTML = 'Result: Error occurred: ' + e.message;
}
});
}
With loadfile funcion i choose my image, and with Uploadfile function i upload the image with ajax.
if i use it alone its work perfect and upload the image to the location.
but when i try to add this code to my code, it make alot of errors.
in my code i send to back end all the forms in the pug file:
$('#account-form').ajaxForm({
error : function(e){
if (e.responseText == 'title-empty'){
av.showInvalidTitle();
}
},
success : function(responseText, status, xhr, $form){
if (status == 'success')
{
$('.modal-alert').modal('show');
console.log(responseText)
}}
});
i try to merge the ajaxform with the ajax but when i merege the formdata or i send in ajaxform the data of the file is send error.
how can i merge the codes?
thanks for helping.
Try to submit form it will submit form with your image.
let form = $("#form_id");
$.ajax({
url : $(form).attr("action"),
type: "POST",
dataType: "json",
processData: false,
contentType: false,
cache: false,
data: new FormData(form[0]),
success:function(data){
},
error: function (xhr, status, e) {
}
});
#Yogesh Patel
when i use this code:
$('#account-form-btn2').on('click', function(e) {
let form = $("#account-form");
$.ajax({
url: $(form).attr("action"),
type: "POST",
dataType: "json",
processData: false,
contentType: false,
cache: false,
data: new FormData(form[0]),
error: function (e) {
if (e.responseText == 'title-empty') {
av.showInvalidTitle();
}
},
success: function (responseText, status, xhr, $form) {
if (status == 'success') {
$('.modal-alert').modal('show');
}
}
});
});
for some reason it sends the values to "routes" three times.
and it doesn't catch the erorrs or success.
and it sends me to a white window with the value of the callback.
if needed, i can send the function that gets the values and returns them (app.post).

File upload using jquery/ajax for REST API

I was trying to upload file to a remote server using REST api by ajax/jquery with the following script, but it returns 400 error with a Bad request. I have tested the end point with curl, which is giving correct response and file is being uploaded.
$(document).ready(function () {
$("#btnSubmit").click(function (event) {
//stop submit the form, we will post it manually.
event.preventDefault();
fire_ajax_submit();
});
});
function fire_ajax_submit() {
// Get form
var form = $('#fileUploadForm')[0];
alert(form.files[0]);
var data = new FormData(form);
data.append("CustomField", "This is some extra data, testing");
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "http://10.13.20.166:5332/fileUploadtoFolder",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
$("#result").text(data);
console.log("SUCCESS : ", data);
$("#btnSubmit").prop("disabled", false);
},
error: function (e) {
$("#result").text(e.responseText);
console.log("ERROR : ", e);
$("#btnSubmit").prop("disabled", false);
}
});
}
Change your code 👇
var data = new FormData(form);
Use this code 👇
// Create an FormData object
var data = new FormData(document.getElementById("fileUploadForm"));
Try again

Paginate data in view without repeating sql queries using ASP.NET mvc

I have a large dataset from a stored procedure that I want to display in pages on an ASP.NET webpage. I can't make demands of the DBAs, so asking them to support pagination on their end isn't possible. The data is currently being displayed in a widget that's being populate by an ajax call to an action in my controller. I want the user to be able to change the page and page size without the stored procedure firing again, but I don't know how to pass the data/model from the getData call to the paginateData call.
Ajax:
require(["jquery", "ajax"], function ($, ajax) {
getData: function () {
ajax.html({
url: Router.action("Widgets", "GetData"),
interval: 3000,
maxAttempts: 20,
cache: false,
success: function (response) {
$('#view-dataList', $context).replaceWith(response);
}
});
}
paginateData: function () {
ajax.html({
url: Router.action("Widgets", "PaginateData", {pageNumber: pageNumber, pageSize: pageSize, data: ??????}),
interval: 3000,
maxAttempts: 20,
cache: false,
success: function (response) {
$('#view-dataList', $context).replaceWith(response);
}
});
}
}
Widgets Controller:
[Route("GetData")]
public ActionResult GetData()
{
var model = new DataModel();
var service = new SqlService();
var customerID = Identity.Current.OptaviaID.ToString();
model.RecentActivities = service.LoadData();
return PartialView(model);
}
[Route("PaginateData")]
public ActionResult PaginateData(int pageNumber, int pageSize, IList<Data> data)
{
var model = new DataModel();
var page = model.page.Skip((pageNumber - 1) * pageSize).Take(pageSize);
model.Data = page;
return PartialView(model);
}
What is a good way to design this?
I ended up changing the return values of GetData and PaginateData in the controller to return the model in json to be stored in the javascript withing the ajax success function and added a new method DisplayData to return the unserialized PartialView. I changed PaginateData and DisplayData to HttpPost calls accepting the model that we stored in javascript.
Javascript (notice that getdata, paginate, and display are tethered together via success):
require(["jquery", "ajax"], function ($, ajax) {
var currentData = null;
var currentPage = null;
var actions = {
getData: function () {
ajax.html({
url: Router.action("Widgets", "GetData"),
interval: 3000,
maxAttempts: 20,
cache: false,
success: function (response) {
currentData = response;
actions.paginateData();
}
});
},
paginateData: function () {
ajax.html({
url: Router.action("Widgets", "DisplayData"),
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
interval: 3000,
maxAttempts: 20,
cache: false,
data: JSON.stringify({ data: currentData, startIndex: 0, pageSize: 10 }),
success: function (response) {
currentPage = response,
actions.displayData();
}
});
},
displayData: function () {
ajax.html({
url: Router.action("Widgets", "PaginateData"),
type: 'POST',
contentType: 'application/json; charset=utf-8',
interval: 3000,
maxAttempts: 20,
cache: false,
data: JSON.stringify(currentPage),
success: function (response) {
$('#view-dataList', $context).replaceWith(response);
}
});
}
}
}
Controller:
[Route("GetData")]
public ActionResult GetData()
{
var model = new DataModel();
var service = new SqlService();
var customerID = Identity.Current.OptaviaID.ToString();
model.Data = service.LoadData();
Content(JsonConvert.SerializeObject(model), "application/json");
}
[HttpPost]
[Route("PaginateData")]
public ActionResult PaginateData(DataModel data, int pageNumber, int pageSize)
{
data.Data = data.Data.Skip((pageNumber - 1) * pageSize).Take(pageSize);
Content(JsonConvert.SerializeObject(data), "application/json");
}
[HttpPost]
[Route("DisplayData")]
public ActionResult DisplayData(DataModel data)
{
return PartialView(data);
}
Now in my javascript I can call getData on page load to get the data, get the default page and count, and display it, but I can also call paginateData when the user changes the page or changes the page size to get the new page and display it without querying the database again which answers this question.

Passing HttpPostedFileBase and other variables in ajax POST to mvc controller

I have been trying to post a file and some variables to my controller action using ajax, but I am getting null parameters for both of my variables.
Below is my ajax call
$("#btn-upload").on("click", function () {
var rows =$("[name='rows']").val();
var formData = new FormData($('#excel-upload-form')[0]);
var Data = formData+"&rows="+rows;
$.ajax({
url: '/MVC/UploadExcel/UploadExcel',
type: 'POST',
data: Data,
cache: false,
contentType: false,
processData: false,
success: function (result) {
if (result=='True') {
$(".alert-success").show();
}
else {
$(".alert-danger").show();
}
},
error: function (jqXHR, textStatus, errorThrown) {
$(".alert-danger").show();
},
});
});
and my controller action is
[HttpPost]
public bool UploadExcel(HttpPostedFileBase uploadedFile, int? rows)
{
var excelUtility = new ExcelUtilityService();
bool success=false;
if ((uploadedFile != null || uploadedFile.ContentLength > 0)&& rows !=null)
{
success = excelUtility.ProcessFile(uploadedFile, rows);
}
return success;
}
If I pass only the file parameter in my ajax call it works fine but when I try to do it with multiple parameters e.g 'rows' in my code, both of the parameters become null in my controller action while post.
In order to add values to a FormData object, you need to use .append().
Modify your script to
$("#btn-upload").on("click", function ()
var rows =$("[name='rows']").val();
var formData = new FormData($('#excel-upload-form')[0]);
formData.append('rows', rows); // modify
$.ajax({
url: '/MVC/UploadExcel/UploadExcel',
type: 'POST',
data: formData, // modify
cache: false,
contentType: false,
processData: false,
success: function (result) {
....
Using the script modification from Stephen:
$("#btn-upload").on("click", function ()
var rows =$("[name='rows']").val();
var formData = new FormData($('#excel-upload-form')[0]);
formData.append('rows', rows); // modify
$.ajax({
url: '/MVC/UploadExcel/UploadExcel',
type: 'POST',
data: formData, // modify
cache: false,
contentType: false,
processData: false,
success: function (result) {
....
If linking to parameters directly doesn't work with the formData.append() method above, I would recommend accessing them via:
Request["key-used-to-append"]
Example with your controller (rows variable assignment):
[HttpPost]
public bool UploadExcel(HttpPostedFileBase uploadedFile)
{
var excelUtility = new ExcelUtilityService();
var rows = Request["rows"];
bool success=false;
if ((uploadedFile != null || uploadedFile.ContentLength > 0)&& rows !=null)
{
success = excelUtility.ProcessFile(uploadedFile, rows);
}
return success;
}

Passing more then 1 value to webmethod using FormData via Ajax

I'm trying to pass the uploaded image + two additional parameters to my web service using the FormData method from my Ajax method as shown here:
var formData = new FormData();
formData.append('file', $('#photo')[0].files[0]);
formData.append('u', "test");
formData.append('s', "Testing");
My ajax call is outlined like so:
$.ajax({
url: "/admin/WebService/test.asmx/UploadImage",
type: "POST",
processData: false,
contentType: false,
data: formData,
success: function (response) {
console.log(response);
},
error: function (er) {
alert(er);
}
});
Which calls this webmethod:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string UploadImage()
{
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var t= System.Web.HttpContext.Current.Request.Files["s"];
var c= System.Web.HttpContext.Current.Request.Files["u"];
var p = System.Web.HttpContext.Current.Request.Files["file"];
}
else
{
return "Error";
}
return "Error";
}
The issue I'm having is the parameters 'u' and 's' are null yet when referencing file I'm able to get its value.
Whilst searching the web I was under the impression you can specify as many key/values are required when using this approach unless I have been misinformed? can someone please shed some light into why these two parameters are null? Thanks in advance.
This works for me:
JavaScript
var formData = new FormData();
formData.append("UserId", userId);
formData.append("RequestPhoto", imageFile);
formData.append("RequestVoiceRecord", voiceFile);
formData.append("Latitude", latitude);
formData.append("Longitude", longtitude);
$.ajax({
type: "POST",
url: "/User/CreateRequest",
data: formData,
contentType: false,
processData: false,
success: function () {
alert("OK");
},
error: function () {
alert("Error");
}
});
Controller:
public class UserController : ApiController
{
[HttpPost]
public int CreateRequest()
{
// HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
var req = new UserRequest
{
UserId = Guid.Parse(httpRequest.Form["UserId"]),
Photo = httpRequest.Files["RequestPhoto"],
VoiceRecord = httpRequest.Files["RequestVoiceRecord"]
Latitude = float.Parse(httpRequest.Form["Latitude"]),
Longitude = float.Parse(httpRequest.Form["Longitude"]),
};
You should create one json instead of create this stuff, add whatever keys you want to sent via ajax.
var formData = {'u':'value','s':'value'}
$.ajax({
url: "/admin/WebService/test.asmx/UploadImage",
type: "POST",
processData: false,
contentType: false,
data: JDON.Stringify(formData),
success: function (response) {
console.log(response);
},
error: function (er) {
alert(er);
}
});
try using this way.

Resources