Pass array of string from ajax to controller - asp.net-mvc

I need to send an array of string from ajax to a controller and I need to return a file to download. I already look and everywhere says that the same solution, but I can not make it work. I have put a break on the controller, but never entered.
The controllers are in different project.
SOLUTION
PROJECT 1
Controllers
ApiControllers
RenderMvcControllers
SurfaceControllers
ExportController
PROJECT 2
function GetData() {
var stringArray = new Array();
stringArray[0] = "item1";
stringArray[1] = "item2";
stringArray[2] = "item3";
var postData = { values: stringArray };
$.ajax({
type: "POST",
url: "/umbraco/Surface/Export/HandleDownloadFile",
data: postData,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert();
alert(data.Result);
},
error: function (data) {
alert("Error: " + data.responseText);
},
});
}
class ExportController : SurfaceController
{
[HttpPost]
public ActionResult HandleDownloadFile(string[] productList)
{
return CurrentUmbracoPage();
}
}

If you are sending array values via AJAX, you'll need to ensure that the traditional attribute is set to true (which allows this behavior) and that your parameter is named to match what MVC expects that it should be productList :
// This is important for passing arrays
traditional: true,
Secondly, since you are posting this to a different project, you may need to explicitly define where the project is running by using an absolute URL (as a relative one would be used by default and would likely point to your current project) :
url: "{your-other-project-url}/umbraco/Surface/Export/HandleDownloadFile",
Finally, you may want to try removing the contentType attribute as that is used to define what the server expects to receive in it's response. Since you aren't expecting JSON back (and instead are expecting a file), you could consider removing it.
$.ajax({
type: "POST",
// Consider making the URL absolute (as it will be relative by default)
url: "/umbraco/Surface/Export/HandleDownloadFile",
// This is important for passing arrays
traditional: true,
// Make sure that productList is used as it matches what your Controller expects
data: { productList: stringArray }.
dataType: "json",
success: function (data) {
alert(data.Result);
},
error: function (data) {
alert("Error: " + data.responseText);
},
});

Related

Save Image Into Database using api

I have a web application with many layers (DAL, BLL, SL, UI), each layer in a separate project.
I am consuming a Web API in the presentation layer (UI) using ajax, where I am using single page application.
Example: in index action in home controller in the presentation layer(UI) only refers to view:
public class MaCityController : Controller
{
public IActionResult Index()
{
return View("~/Views/Mainten/MasterFile/MaCity/Index.cshtml");
}
}
and in this view I am doing my CRUD operation using Web API and Ajax:
function Add() {
var NameAr = $('#NameAr').val();
var NameEn = $('#NameEn').val();
var Image = $('#FileName').val();
var newData = new Object();
newData.NameAr = NameAr;
newData.NameEn = NameEn;
newData.Image=Image;
$.ajax({
type: "POST",
url: APIURL + "api/MaCity/Add",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(newData),
success: function () {
$('#myModal').modal('hide');
debugger;
loadData();
},
failure: function (data) {
alert(data.statusText);
},
error: function (data) {
alert(data.statusText);
}
});
}
}
My posting code in Sl as
[HttpPost]
public IActionResult Add(City scItem)
{
_unitOfWork.GetRepository<City>().Add(scItem);
_unitOfWork.SaveChanges();
return Ok();
}
Where api In another Application with different port than presentation Layer (UI)
and any dealing with database occurs in SL (NO DEAL WITH DATA IN UI).
I need to upload an image to the server and save (image server url) into the database.
I read many articles but I can't find solution to solve my problem.
Any help?
Have you tried checking if the file is getting added to the json request object? there are a few ways you can try this, e.g using a tool like Telerik Fiddler
inside your json post method, check if there are any files in your form
var file =$(this).prop('files')[0];
A somewhat example would be the following
add the image to FormData
formdata = new FormData();
if($(this).prop('files').length > 0)
{
var file =$(this).prop('files')[0];
formdata.append("image", file);
}
Then finally post the post the image
jQuery.ajax({
url: "api_path,
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (result) {
// if all is well
// play the audio file
}
});
You can also try sending the data from your Controller(assuming you are using some MVC flavour)

pass enum parameter from Ajax Jquery to MVC web api

I need to call a web api, this web api method is accepting two parameter one is enum type and another is int. I need to call this api using Ajax Jquery. How to pass enum paramter.
API Code
[HttpGet]
public HttpResponseMessage GetActivitiesByType(UnifiedActivityType type, int pageNumber)
{
var activities = _activityService.GetAllByType(type, pageNumber);
return Request.CreateResponse(HttpStatusCode.OK, activities);
}
My Ajax Call Code:
var jsonData = { 'type': 'Recommendation', pageNumber: 0 };
$.ajax({
type: 'get',
dataType: 'json',
crossDomain: true,
url: CharismaSystem.globaldata.RemoteURL_ActivityGetAllByType,
contentType: "application/json; charset=utf-8",
data: jsonData,
headers: { "authorization": token },
error: function (xhr) {
alert(xhr.responseText);
},
success: function (data) {
alert('scuess');
}
});
Any Suggestions..
An enum is treated as a 0-based integer, so change:
var jsonData = { 'type': 'Recommendation', pageNumber: 0 };
To this:
var jsonData = { 'type': 0, pageNumber: 0 };
The client needs to know the index numbers. You could hard code them, or send them down in the page using #Html.Raw(...), or make them available in another ajax call.
You can not pass enum from client side. Either pass string or int and on the server side cast that value to enum. Something like,
MessagingProperties result;
string none = "None";
result = (MessagingProperties)Enum.Parse(typeof(MessagingProperties), none);
Or you can do something similar to this post

Ajax Request issue with ASP.NET MVC 4 Area

Today i discovered something weird, i have regular asp.net mvc 4 project with no such ajax (just post, get). so today i need ajax request, i did an ajax action with jquery in controller and it didn't work out. Here is my code
Areas/Admin/Controllers/BannersController
public JsonResult SaveOrder(string model)
{
bool result = false;
if (!string.IsNullOrEmpty(model))
{
var list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<int>>(model);
result = repository.SaveOrder(list);
}
return Json(result, JsonRequestBehavior.AllowGet);
}
View side (Its in area too)
$(document).ready(function () {
$("#saveOrder").click(function () {
var data = JSON.stringify($("#list_banners").nestable('serialize'));
$.ajax({
url: '#Url.Action("SaveOrder", "Banners", new { area = "Admin" })',
data: { model: data },
success: function (result) {
if (result) {
toastr.success('Kaydedildi.');
}
else {
toastr.error('kaydedilemedi.');
}
},
error: function (e) {
console.log(e);
}
});
});
});
i've already tried everything i know, which is $.post, $.get, ajax options, trying request from out of area etc.. just request can't reach action
and here is the errors ,
http://prntscr.com/297nye
error object
http://prntscr.com/297o3x
Try by specifying the data format (json) you wand to post to server like and Also change the way you pass data object in JSON like this :
var data = $("#list_banners").nestable('serialize');
$.ajax({
url: '#Url.Action("SaveOrder", "Banners", new { area = "Admin" })',
data: JSON.stringify({ model: data }),
dataType: 'json',
contentType: "application/json",
...
I had same issue, but after spending too much time, got solution for that. If your request is going to your specified controller, then check your response. There must be some problem in your response. In my case, response was not properly converted to JSON, then i tried with passing some values of response object from controller using select function, and got what i needed.

Controller Action cannot be called from $.Ajax javascript

In MVC, I have written an action in the controller for getting values. The action is as follows..
public void poolshapepdf(List<String> values)
{
...
}
To pass the parameter values to the controller action i pass the values from javascript..
the code is the below,
$.ajax({
type: 'POST',
url: rootDir + "IngroundCalculation/poolshapepdf",
data: { values: collectionPSElmt },
traditional: true,
});
Here collectionPSElmt is an array.
collectionPSElmt[index] = poolshapeValue[index] + "-" + psFeet[index] + "-" + psInch[index];
Here the issue is the controller action cannot be called from the javascript $.Ajax(..).
How do I fix this issue?
You calling the controller by POST and JSON data:
[HttpPost]
public JsonResult poolshapepdf(DataClass[] items)
{
}
Now, make a proper call to your url.
specify the data type as json and always go for success function.
using that you can easily crack the report.
$.ajax({
url: '#Url.Action("poolshapepdf", "IngroundCalculation")',
type: "POST",
dataType: 'json',
data: collectionPSElmt ,
contentType: "application/json; charset=utf-8",
success: function (result) {
alert("Working..");
}
});
And at Controller Side,
[HttpPost]
public JsonResult poolshapepdf(DataClass[] items)
{
// Your Code here....
}

asp.net mvc 3 json values not recieving at controller

the problem is that i am not able to recieve any value in the controller . what could be wrong? the code is here.
$('#save').click(function () {
var UserLoginViewModel = { UserName: $('vcr_UserName').val(),
Password: $('vcr_Password').val()
};
$.ajax({
url: "/User/Login",
data: JSON.stringify(UserLoginViewModel),
contenttype: "application/json; charset=utf-8",
success: function (mydata) {
$("#message").html("Login");
},
error: function () {
$("#message").html("error");
},
type: "POST",
datatype: "json"
});
return false;
});
});
[HttpPost]
public ActionResult Login(UserLoginViewModel UserLoginViewModel)
{
}
As you're using MVC3 - you should be able to take advantage of the built in JSON model binding.
Your code example has a couple of typos: contentType and dataType are lowercase...(they should have an uppercase "T")
jQuery ajax docs
After you POST up the correct contentType/dataType, MVC should automatically bind your object to the posted JSON.
You're going to need an action filter or similar to intercept the json from the post body.
Here's a starter
Provider Factory
but here is the article that sorted this for me On Haacked
It is good if you know the type you are deserialising into up front, but if you need polymorphism you'll end up using these ideas in an action filter.

Resources