How to call Javascript function on Url.Action on Kendo toolbar? - javascript

I have a kendo grid with a toolbar . I added a link to download from the toolbar and now the problem is i can't call Javascript function which goes to the controller with data.
How can i call java script function on Url.Action ?
Toolbar
.ToolBar(toolBar => toolBar.Template("<a onclick='getData()' href ='" + Url.Action("", "", null, "https") + "?SeletectOrders=#= SeletectOrders#'" + ">Download Selected Orders</a>"))
If i put controller name and function, it pass an empty data to the controller and download empty file which shows at the bottom on browser. I am really not sure if am doing this correctly
Javascript function which goes to the controller
function getData(SeletectOrders)
{
$.ajax({
url: '#Url.Action("myAction", "mycontroller")',
type: "GET",
contentType: 'application/json; charset=utf-8',
dataType: "text",
data: { SeletectOrders: SeletectOrders },
traditional: true,
async: false,
cache: false,
complete: function (data) {
},
error: function () {
}
})
}
Controller
[HttpGet]
public virtual ActionResult myAction(string[] SeletectOrders)
{
List<string> ListPossDetails = new List<string>();
if (SeletectOrders != null)
{
string[] OrderArray = SeletectOrders;
foreach (var list in OrderArray)
{
ListPossDetails.Add(list);
}
}
//download methods here
Response.AppendHeader("Content-Disposition", "attachment; filename=" + possFilename);
ListPossDetails = null;
return File(fileBytes, type, possFilename);
}

Related

Ajax POST int to MVC

I'm trying to POST an INT with Ajax to my MVC controller.
The script debugging confirms that my variable is an INT with a value (for example 8 and not a string "8"). All lines of code are executed and
I recive my Alert error message.
I've got a breakpoint inside of my Action in the controller but I never get that far. I get a notice in my Action that a request failed, but it only say
"POST Order/Delete". My Controller name is OrderController and Action name is Delete.
My JavaScript:
//Delete order
$(".deleteOrder").on("click", function () {
var id = parseInt($(this).attr("id"));
if (id !== null) {
$.ajax({
url: "/Order/Delete",
method: "POST",
contentType: "application/JSON;odata=verbose",
data: id ,
success: function (result) {
alert("Ok")
},
error: function (error) {
alert("Fail");
}
});
}
});
My MVC Action
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
List<OrderRow> lstOrderRow = new List<OrderRow>();
lstOrderRow = db.OrderRows.Where(x => x.OrderId == id).ToList();
foreach(var row in lstOrderRow)
{
db.OrderRows.Remove(row);
}
Order order = new Order();
order = db.Orders.Find(id);
db.Orders.Remove(order);
db.SaveChanges();
return RedirectToAction("index");
}
You should either use the url like this by removing data field
url: "/Order/Delete/" + id,
or send the id in data as below
data: {id: id},
This works for me:data: JSON.stringify({ id: id})
dataType: "json",
contentType: 'application/json; charset=utf-8',

How to get data from json in lightgallery jquery?

I face with a problem in use lightgallery with jquery .When I use constant value for src and thumb it works great, but in the opposite it doesn't work with json . I see this kind of error in firebug.
Error
-data-src is not provided on slide item
HTML Code
<a id="dynamic" href>Open lightGallery</a>
$('#dynamic').on('click', function(e) {
var arr='';
$.ajax({
type: 'post',
url: "#Url.Action("ShowMenuGallery", "Ads")",
contentType: 'application/json; charset=utf-8',
data: '{"ID":"' + #Model.ID + '"}',
traditional: true,
success: function (data) {
arr=data;
console.log(arr);
}
});
$('#dynamic').lightGallery({
dynamic: true,
html:true,
dynamicEl: JSON.stringify(arr)
})
});
Controller.cs
public ActionResult ShowMenuGallery(int id)
{
ViewBag.guid = Guid.NewGuid();
List<string> menuImage = new List<string>();
ReturnImages(((Guid)ViewBag.guid).ToString(), id, ref menuImage);
List<MyClass> data = new List<MyClass>() { new MyClass() { src =menuImage[0] , thumb = menuImage[0] } };
var json = Newtonsoft.Json.JsonConvert.SerializeObject(new
{
operations = data
});
return Json(json);
}
public class MyClass
{
public string src { get; set; }
public string thumb { get; set; }
}
Try once this code
jQuery(document).ready(function($) {
$("#dynamic").on("click", function(e) {
$.ajax({
type: "post",
url: "#Url.Action("ShowMenuGallery", "Ads")",
dataType: "json",
data: {ID: "#Model.ID"},
traditional: true,
success: function (data) {
$("#dynamic").lightGallery({
dynamic: true,
html:true,
dynamicEl: JSON.stringify(data)
});
}
});
});
});
For more information see https://boxoverflow.com/get-json-jquery-ajax/

The requested resource does not support http method 'DELETE'

I have a web service created by Asp API, and i am trying to consume it by javascript ajax caller .. it works fine with GET & POST .. but when i tried to call DELETE function it returns message [The requested resource does not support http method 'DELETE'.]
and this is my code
Server code (API C#)
[HttpDelete]
public bool Delete(int id)
{
try
{
var model = db.PostsLikes.First(f => f.PostLikeID == id);
db.PostsLikes.Remove(model);
db.SaveChanges();
return true;
}
catch (Exception)
{
return false;
}
}
Client code (Javascript)
function (postLikeid) {
var result = $.ajax({
url: "/api/PostsLikes/",
type: "DELETE",
async: false,
data: postLikeid ,
contentType:"application/json"
}).responseText;
return result;
}
Problem is your IIS configuration is not accepting DELETE verbs. In the Handler Mappings section of IIS you can add the Delete verb.
Add it in delete method.
[HttpDelete]
[Route("api/PostsLikes/{id}")]
function DeleteFruitRecord(FruitID) {
var del = confirm("Are you sure you want to delete this recored?");
if (del) {
$.ajax({
type: "DELETE",
url: "api/FruitRec/DeleteFruit" + FruitID,
contentType: "json",
dataType: "json",
success: function (data) {
alert("Successsfully deleted…. " + FruitID);
GelAllEmployees();
},
error: function (error) {
alert(error.responseText);
}
});
}

Passing an array of Javascript classes to a MVC controller?

I am trying to pass an array of services to my controller.
I've tried a bunch of different ways to get it work, serializing the data before going to controller, serializing each service, only thing that seems to work is changing the controller parameter to string and serializing array, then using JsonConvert, but I'd rather not do that.
With the specified code, I am getting the correct number of items in the List, but they all contain a service id with an empty guild, and service provider id is null.
Any ideas?
Javascript
function ServiceItem() {
this.ServiceProviderID = 'all';
this.ServiceID = '';
}
var selecteditems= (function () {
var services = new Array();
return {
all: function() {
return services;
},
add: function(service) {
services.push(service);
}
};
})();
var reserved = [];
$.each(selecteditems.all(), function(index, item){
reserved.push({ ServiceID: item.ServiceID, ServiceProviderID: item.ServiceProviderID});
});
getData('Controller/GetMethod', { items: reserved }, function(result) {
});
var getData = function (actionurl, da, done) {
$.ajax({
type: "GET",
url: actionurl,
data: da,
dataType: "json",
async: true,
success: function (d) {
if (typeof (done) == 'function') {
var str = JSON.stringify(d);
done(JSON.parse(str));
}
}
});
};
Controller
public JsonResult GetMethod(List<CustomObject> items)
{
}
Custom Object
public class CustomObject
{
public Guid ServiceID {get;set;}
public Guid? ServiceProviderID {get;set;}
}
Set the content-type and use POST instead of GET (as it is a list of complex type objects). mark your action with HttpPost attribute too.
See if this works:-
$.ajax({
type: "POST",
url: actionurl,
data: JSON.stringify(da),
dataType: "json",
contentType: 'application/json',
async: true,
success: function (d) {
if (typeof (done) == 'function') {
var str = JSON.stringify(d);
done(JSON.parse(str));
}
}
});

How to pass string value from javascript to function in ASHX

I'm used this code to pass parameter from jQuery to ASHX, actually I want to upload file using Uploadify Plugin and send Parameter named 'Id' to ASHX
function CallHandler() {
$.ajax({
url: "PIU.ashx/MyMethod",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { 'Id': '10000' },
responseType: "json",
success: OnComplete,
error: OnFail
});
return false;
}
function OnComplete(result) {
alert(result);
}
function OnFail(result) {
alert('Request Failed');
}
and this ASHX code:
public void ProcessRequest(HttpContext context)
{
var employee = Convert.ToInt32(context.Request["Id"]);
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string serEmployee = javaScriptSerializer.Serialize(employee);
context.Response.ContentType = "text/html/plain";
context.Response.Write(serEmployee);
parent MyParent = (parent)context.Session["mahdZNUparent"];
//the file data is the file that posted by Uploadify plugin
HttpPostedFile PostedFile = context.Request.Files["Filedata"];
string FileName = PostedFile.FileName; // whene i comment this line, the code works
// properly, but when uncomment this line, the code get to 'Request Failed'
}
public bool IsReusable
{
get
{
return false;
}
}
how can I Solve this problem!!!!!!!
You may want to take a loot at this: http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/
And this one too: Using jQuery for AJAX with ASP.NET Webforms

Categories

Resources