pass dict with array as value to controller - c#

This code returns keys and values from my dict
$.map(dict, function (value, key) {
console.log(key, value);
});
output:
0 ["19,0,0,0", "23,0,0,0", "21,0,0,0", "22,0,0,0", "20,0,0,0"]
1 ["68,0,0,0", "69,0,0,0", "70,0,0,0", "71,0,0,0", "72,0,0,0", "73,0,0,0", "74,0,0,0", "75,0,0,0"]
2 ["115,0,0,0", "114,0,0,0"]
So, in my opinion it is a Dictionary <string,string[]>
I want to pass the dict to controller
$.ajax({
url: '/Home/SomeAction',
type: 'GET',
data: { categoryId: categoryId, traitValues: dict }
});
public ActionResult SomeAction(int categoryId, Dictionary<string,string[]> traitValues){...}
And here is a problem. In controller key dictionary is ok (0,1,2). But value is empty.
So how I can pass my dict from js to controller?

Related

Why ajax call doesn't bind to int[] with jquery .post()

Here is my ajax call:
var idsOfRecordsToBeDeleted = [];
$("#container :checked").each(
function (index) {
idsOfRecordsToBeDeleted.push($(this).attr('id'));
});
var parametersList = { param1: 123456, param2: idsOfRecordsToBeDeleted };
$.post("/Home/Index", parametersList, function (returnedData) {
alert(returnedData);
});
and there is my controller:
[Authorize]
[HttpPost]
public virtual ActionResult Index( int param1, int[] param2)
{
return null;
}
and param1 is OKAY but param2 is always null. Can you help?
You can turn traditional on for your jQuery post to allow for shallow array serialization.
jQuery.ajaxSettings.traditional = true;
var parametersList = { param1: 123456, param2: [1, 2, 3, 4] };
$.post("/Home/Index", parametersList, function (returnedData) {
alert(returnedData);
});
If you would like to apply traditional mode to only this post, you can add it with $.ajax.
var parametersList = { param1: 123456, param2: [1, 2, 3, 4] };
$.ajax({
url: "/Home/Index",
type: 'POST',
data: parametersList
traditional: true
});
Since jQuery 1.8, ajax calls will recursively serialize all objects by defaulting the traditional flag to false.
As a result, deep objects end up getting serialized into a string that represents this object structure:
param2[]=1&param2[]=2&param2[]=3&param2[]=4&=param2[]=5
ASP.NET MVC doesn't know how to handle this format. By setting traditional to true, we preserve the structure that ASP.NET MVC expects:
param2=1&param2=2&param2=3&param2=4&param2=5
EDIT:
Based on how you are building your array (attr returns a string), you will end up with an array of strings, not numbers, meaning that MVC will not deserialize your array.
You can confirm the type by inspecting the first element of idsOfRecordsToBeDeleted.
typeof(idsOfRecordsToBeDeleted[0])
Update your controller method to the following signature:
public virtual ActionResult Index( int param1, string[] param2)
Serialize the array to a string, then deserialize it on the server.
Client:
param2: [1, 2, 3, 4].join(',');
Server (Change param2 type to string instead of int[]):
int[] param2Parsed = param2.Split(',').Select(s => int.Parse(s)).ToArray();

Can a json object's value and key be set in controller action in MVC?

Is it possible for me to get the same SelectListItems in this list:
public static List<SelectListItem> GetAreaApprovingAuthorities(int id)
{
List<Employee> approvingAuthorities = new List<Employee>();
using (var db = new TLMS_DBContext())
{
approvingAuthorities = db.Employees.Where(e => e.UserRoleID > 1 && e.PersonnelAreaID == id).ToList();
}
List<SelectListItem> returned = new List<SelectListItem>();
foreach (Employee emp in approvingAuthorities)
{
returned.Add(new SelectListItem { Text = string.Format("{0} {1}", emp.FirstName, emp.LastName), Value = emp.ID.ToString() });
}
return returned;
}
and pass them into a select list using Json?
Here is the controller action where the List is acquired:
public JsonResult GetApprovingAuthorities(int id)
{
return Json(TLMS_DropDownLists.GetAreaApprovingAuthorities(id),JsonRequestBehavior.AllowGet);
}
Here is where the json object is iterated through and then passed to the select list (this is triggered when another select list's value is changed):
$.ajax({
type: 'GET',
data: { id: selectedValue },
url: '#Url.Action("GetApprovingAuthorities")',
contentType: "application/json; charset=utf-8",
global: false,
async: false,
dataType: "json",
success: function (jsonObj) {
$('#aa').empty();
$.each(jsonObj, function (key, value) {
$('#aa').append($("<option/>", {
value: key.Text,
text: value.Text
}));
});
}
});
This is working to populate the "aa" select list and I am receiving the select list's selected item via the FormCollection in a controller action, but I cannot capture the original ID from the "GetAreaApprovingAuthorities" SelectListItem's Value. Is there a way that I can make this happen?
When you're iterating on the jsonObj it should be like this
//the first parameter is just the index of the iteration
//and the second one is the json object (SelectListItem)
$.each(jsonObj, function (index, obj) {
$('#aa').append($("<option/>",
{
value: obj.Value,
text: obj.Text
}));
});

Send data from ajax to c# server

I've created a dictionary on cliend side and want to send it on sever side. In my script, dictionary is created correctly, but I'm not sure abount my ajax code.
$("#btnSubmit").click(function () {
var sendList = new Array();
var elems = $(".elemValue");
$.each(elems, function (key, value) {
if (value.attributes.elemName.nodeValue != "PhotoImg") {
sendList[value.attributes.elemName.nodeValue] = value.attributes.value.nodeValue;
}
});
var data = JSON.stringify({dict : sendList});
$.ajax({
type: "GET",
url: "dataloader.aspx/GetData",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result){
alert(result.d);
}
});
});
On server side I wrote
[System.Web.Services.WebMethod]
public static string GetData(Dictionary<string,string> dict)
{
Dictionary<string, string> serverDict = new Dictionary<string, string>();
serverDict = dict;
string result = "";
foreach (var value in dict)
{
result += "The key is:" + value.Key + "The value is:" + value.Value;
}
return result;
}
Where are my mistakes, and how can I fix them? Help, please=)
I don't think it's possible to create a Dictionary from JSON. At least not without a lot of work. I would try changing it from a Dictionary to a List<KeyValuePair<string,string>> and see if it deserializes for you.
Reference for KeyValuePair
Once you've done that if you still need the Dictionary you can convert it fairly easily.
var Dictionary = new Dictionary<string,string>();
foreach(var KVP in List) Dictionary.Add(KVP.Key, KVP.Value);
Couple of things here:
You need to allow GET verb explicitly:
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod(UseHttpGet=true)]
You are returning plain text from the server, which means that this line:
dataType: "json"
won't let jQuery parse the response correctly. You should either remove this line, or build response in JSON format.

Array Passed to Controller Received as NULL

I'm using $.post() to post an array of integer values to my controller.
Here's how I construct my array:
var ratings = [];
$('#ratings input[name=newReviewRatings]').each(function () {
ratings.push($(this).val());
});
Here's how I'm posting it to the controller:
$.post('#Url.Action("CreateReview", "Provider")',
{
id: providerId,
ratings: ratings,
comment: comment
});
Here's the form data that gets posted:
{id=437baf29-4196-4966-88de-a8fde87ef68d&ratings%5b%5d=1&ratings%5b%5d=2&ratings%5b%5d=3&ratings%5b%5d=4&ratings%5b%5d=5&comment=Comments}
And here's my controller signature:
public ActionResult CreateReview(Guid id, int[] ratings, string comment)
{
// ....
}
That seems like that should be right, but ratings is always null. Can anyone see what I'm missing?
I also tried string[] ratings and got the same result. I also saw a suggestion to pass the array using JSON.stringify(ratings) but that didn't seem to help either.
In adition to converting the post data to json, you can also set the traditional param to true. This will cause jQuery to use the correct post format for MVC.
jQuery.ajaxSettings.traditional = true;
$.post('#Url.Action("CreateReview", "Home")',
{
id: 'GUID STRING HERE',
ratings: [1, 2, 3],
comment: 'adfef'
});
Try to specify contentType like this:
$.ajax({
url:url,
type:"POST",
data:data,
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){
...
}
})

Adding items to C# dictionary from JavaScript

What, if any, is the accepted way of adding a key-value pair from ASP.NET/JavaScript code to a C# dictionary? TIA.
How I've handled this requirement is to get all the data in a name value pair in javascript, then post this to the server via ajax ...
e.g.
loc is your page,
methodName being the WebMethod in code behind page,
arguments you can populate as
var arguments = '"data":"name1=value1&name2=value2"';
$.ajax({
type: "POST",
url: loc + "/" + methodName,
data: "{" + arguments + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: onSuccess,
fail: onFail
});
On your code behind, create a web method
e.g
[System.Web.Services.WebMethod(EnableSession = true)]
public static string ItemsForDictionary(string data)
{
Dictionary<String, String> newDict = ConvertDataToDictionary(data);
}
I use a generic method to convert this data parameter in codebehind to a Dictionary.
private static System.Collections.Generic.Dictionary<String, String> ConvertDataToDictionary(string data)
{
char amp = '&';
string[] nameValuePairs = data.Split(amp);
System.Collections.Generic.Dictionary<String, String> dict = new System.Collections.Generic.Dictionary<string, string>();
char eq = '=';
for (int x = 0; x < nameValuePairs.Length; x++)
{
string[] tmp = nameValuePairs[x].Split(eq);
dict.Add(tmp[0], HttpUtility.UrlDecode(tmp[1]));
}
return dict;
}
Anyways .. hope this gives you the idea ...
You can't do it directly. You'd have to send the data back to the server using a post-back or ajax call, and then add the data to the Dictionary in the server-side handler.
We could probably be more helpful if you post some of your code to show what you're actually trying to do.

Categories

Resources