pass enum parameter from Ajax Jquery to MVC web api - asp.net-mvc

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

Related

Controller in my MVC project returning null from Ajax Post call

I'm not sure to why the controller is receiving a data from an Ajax call . Could i be doing anything wrong?
[HttpPost]
[Route("Product/UpdateDetails")]
public ActionResult UpdateProduct (ProductModel model) <<// model here is null
{
Product p = new Product
{
ProductId = p.ProductId,
Price = p.Price,
};
return View("_ProductDetail"); }
Ajax call below:
var model = {
ProductId: 1,
Price: 270.99,
};
var json = JSON.stringify(model)
$.ajax({
url: '/Product/UpdateDetails',
type: 'Post',
contentType: "application/json; charset=utf-8",
model: model,
success: function (results) {
}
});
//Model
public class Product
{
public int Id {get;set;}
public double Price {get;set;}
}
Can you guys spot anything that i may be doing wrong in the code above ? I can't see anything that i'm doing wrong.
Try this:
$.ajax({
url: '/Product/UpdateDetails',
type: 'Post',
contentType: "application/json; charset=utf-8",
data: json,
success: function (results) {
}
});
You used JSON.Stringify() on your model, but forgot to use the variable "json" on the ajax call, so the ajax was trying to post a "non-json" model.
Also, there is no model setting in ajax calls, the correct one to post your data is data, as you can see here.

Pass array of string from ajax to controller

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);
},
});

Send data from js to controller

I have this ajax:
function sendData() {
var question = (document.getElementById('question').value).toString();
var c = (document.getElementById('c').value).toString();
$.ajax({
url: '/Home/InsertData',
type: 'POST',
data: {question:question, c:c},
// data: {},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function () {
alert('suc');
},
error: function (error) {
alert('error');
}
});
}
in my HomeController, I have the function:
[HttpPost]
public void InsertData(string question, string c)
//public void InsertData()
{
this.insertDataToCustomers(question, c);
}
when I run it, I got an error of:
POST http://localhost:2124/Home/InsertData 500 (Internal Server Error)
If I didn't ask for input values in InsertData function and didn't send data in the ajax, it works. why can't I send data to InsertData function?
p.s. There are values in question and c
thank you!
Remove this:
contentType: 'application/json; charset=utf-8',
You are not sending any JSON to the server, so this is an incorrect content type for the request. You are sending a application/x-www-form-urlencoded request.
So:
function sendData() {
var question = $('#question').val();
var c = $('#c').val();
$.ajax({
url: '/Home/InsertData',
type: 'POST',
data: { question: question, c: c },
success: function () {
alert('suc');
},
error: function (error) {
alert('error');
}
});
}
Another problem with your code is that you indicated dataType: 'json' which means that you expect the server to return JSON but your controller action doesn't return anything. It's just a void method. In ASP.NET MVC controller actions should return ActionResults. So if you want to return some JSON for example to indicate the status of the operation you could have this:
[HttpPost]
public ActionResult InsertData(string question, string c)
{
this.insertDataToCustomers(question, c);
return Json(new { success = true });
}
Of course you could return an arbitrary object which will be JSON serialized and you will be able to access it in your success AJAX callback.

Received parameter from ajax POST empty in controller + passed parameter in firebug MVC 4

I have looked over the net to figure out what my mistake is. All suggestions I found I tried, without any succes. I access the httppost action in my controller but the parameters stays empty.
AJAX function
var dataPost = { 'id': id, 'val': val };
debugger;
$.ajax({
type: 'POST',
url: '/Extensions/UpdateJson',
data: dataPost ,
contentType: 'json',
success: function () {
alert("succes");
},
error: function () {
alert("error");
}
});
On debug DataPost is populated.
Controller
[HttpPost]
public ActionResult UpdateJson(string id, string val)
{
//do stuff
return Json(true);
}
The parameters I used in my controller have the same name as in my Ajax function. The format passed is json, I have also tried populating my data with:
var dataPost = { 'id': 'id', 'val': 'val' };
But this doesn't make any difference. I have also tried to work with a Class, like -->
Class
public class ScheduleData
{
public string id { get; set; }
public string val { get; set; }
}
Controller
public ActionResult UpdateJson(ScheduleData data)
{//Do something}
Any help would be appreciated. Thanks in advance
The format passed is json
No, not at all. You are not sending any JSON. What you do is
data: { 'id': id, 'val': val }
But as the documentation clearly explains this is using the $.param function which in turn uses application/x-www-form-urlencoded encoding.
So get rid of this contentType: 'json' property from your $.ajax call.
Or if you really wanna send JSON, then do so:
var dataPost = { 'id': id, 'val': val };
$.ajax({
type: 'POST',
url: '/Extensions/UpdateJson',
data: JSON.stringify(dataPost),
contentType: 'application/json',
success: function () {
alert("succes");
},
error: function () {
alert("error");
}
});
Things to notice:
usage of JSON.stringify(dataPost) to ensure that you are sending a JSON string to the server
contentType: 'application/json' because that's the correct Content-Type value.

How to ajax/post JSON array to ASP MVC

Trying to do a post including some JSON data that has an array of integers in it. Pressing the button on my page to perform the post is getting to the action, but the expected data is not there (the two int[] variables are null). Doing a network profile while posting shows that the request body includes data like this:
groups%5B%5D=2&groups%5B%5D=3&alerts%5B%5D=5&alerts%5B%5D=9
Javascript:
$('#modal-save').click(function() {
var selectedGroups = [];
var selectedAlerts = [];
$('input:checked').filter('[data-group="true"]').each(function() {selectedGroups.push($(this).data('id')); });
$('input:checked').filter('[data-group="false"]').each(function() {selectedAlerts.push($(this).data('id')); });
$.ajax({
type:'Post',
dataType: 'json',
url:'#Url.Action("UpdateAlertStores", new { alias = ViewBag.Alias})',
data: {groups: selectedGroups, alerts: selectedAlerts},
});
MVC Action:
[HttpPost]
public bool UpdateAlertStores(string alias, Guid? groupID, Guid? storeID, int[] groups, int[] alerts)
{
return true;
}
add traditional:true
traditional: true,
type:'Post',
dataType: 'json',
url:'#Url.Action("UpdateAlertStores", new { alias = ViewBag.Alias})',
data: {groups: selectedGroups, alerts: selectedAlerts},
after this changing your url looks like:
groups=2&groups=3&alerts=5&alerts=9

Resources