Pass array as query string in jquery - c#

I have created one string array in jquery of name array[] and pushed values to it.
How can I send this array in query string?
For example window.location.href('ViewData?array');
And how can I get back the array data from query string in jquery itself ?
Please advice?

This is very easy to achieve with jQuery as it has a helper function called param().
var myData = {
name: "John Doe",
age: 23,
children: [{
name: "Jane Doe",
age: 13,
children: []
},
{
name: "John Doe Jr.",
age: 16,
children: []
}
],
}
var p = $.param(myData)
The results:
"name=John+Doe&age=23&children%5B0%5D%5Bname%5D=Jane+Doe&children%5B0%5D%5Bage%5D=13&children%5B1%5D%5Bname%5D=John+Doe+Jr.&children%5B1%5D%5Bage%5D=16"
You can use it like so:
window.location = "/MyController/MyAction?" + p;
As for getting parameters from query strings, please refer to the following question: How can I get query string values in JavaScript?
Another thing you can do is use an ajax call, this way you don't have to serialize the data yourself as it is done for you automatically.
$.ajax({
url: "/MyController/MyAction",
data: myData,
dataType: "json",
type: "POST",
success: function(data){
//'data' is your response data from the Action in form of a javascript object
}
})

I think this is what you are looking for. Let me know if I get it wrong. I copied $.parseParams from this link. You can also see working code here
(function($) {
var re = /([^&=]+)=?([^&]*)/g;
var decodeRE = /\+/g; // Regex for replacing addition symbol with a space
var decode = function (str) {return decodeURIComponent( str.replace(decodeRE, " ") );};
$.parseParams = function(query) {
var params = {}, e;
while ( e = re.exec(query) ) {
var k = decode( e[1] ), v = decode( e[2] );
if (k.substring(k.length - 2) === '[]') {
k = k.substring(0, k.length - 2);
(params[k] || (params[k] = [])).push(v);
}
else params[k] = v;
}
return params;
};
})(jQuery);
var s=["abc", "xyz", "123"];
var queryString=$.param({a:s});
console.log("object to query string: ", queryString);
console.log("query string to object: ", $.parseParams(queryString));

Related

undefined error at calling method in controller from jquery ajax

I want to call a method from a controller to calculate a basic arithmetic operation. However, I get only undefined error. My code is
$("#equals3").click(
function () {
let display = $("#calculatorDisplay");
let currentValue = display.val();
$.ajax({
url:'Calculator/EvaluateExpressionAJAX',
type: 'POST',
data: { expression: currentValue },
contentType: 'application/json; charset=utf-8',
success: function (response) {
if (response.success) {
alert(response);
} else {
alert(response.responseText);
}
},
error: function (response) {
alert("error!");
}
});
});
My controller contains
public static Dictionary<string, ArithmeticOperation> EvaulationDictionary = new Dictionary<string, ArithmeticOperation> {
{ "+", (a, b) => a + b},
{ "-", (a, b) => a - b},
{ "*", (a, b) => a * b},
{ "/", (a, b) => a / b},
{ "%", (a, b) => a % b} };
[HttpPost]
public double EvaluateExpressionAJAX(string expression)
{
expression = expression.Trim();
string[] splitExpression = Regex.Split(expression, #"\s+");
double a = Convert.ToDouble(splitExpression[0]);
double b = Convert.ToDouble(splitExpression[2]);
string op = splitExpression[1];
return EvaulationDictionary[op](a, b);
}
Thanks in advance
If you would put a breakpoint in the javascript you'll probably find that MVC/WebApi returns an error page with a message like:
Invalid JSON primitive: expression
The JSON that you post is not valid, it isn't even JSON.
If you would replace that with:
data: "{ \"expression\": \"" + currentValue +"\" }",
That would post valid json to the ActionMethod.
A better option would be to create a JavaScript Object and stringify that, like this:
// create a js object before the Ajax call
let dataObj = { "expression": currentValue };
// change the data you send to this
data: JSON.stringify(dataObj),
And secondly: Take a good look at the url, I can't be sure, but if the page you rendered this from is the same controller and the index method, this probably won't work as you would expect. Change the URL to:
url:'/Calculator/EvaluateExpressionAJAX',
to make it absolute.
And finally, there are lot of possible bugs in the Action method. You can't expect users to supply 3 parts where part 1 and 3 are doubles. So there is a lot of checking missing.
And last but not least, if this is MVC, it is probably best to return ActionResult or some subtype, in this case JsonResult would suit best, from an actionmethod.

LINQ SQL Method not Filling Highcharts

My goal is to create a column highchart that shows the name of various salesman and how much they have sold. I wrote this code to return from my SQL Database the names and the sum of the sales for each salesman:
[HttpPost]
public JsonResult ChartVendedores()
{
//Retorna um JSON contendo o nome do vendedor e o valor por ele vendido, usando inner join pelo id do vendedor.
try
{
var resultado = (from ve in db.tblVendedor
join vn in db.tblVenda on ve.vendedor_id equals vn.vendedor_id
group vn by new
{
ve.vendedor_nome
}into g
select new {
vendedor_nome = g.Key.vendedor_nome,
venda_valor = g.Sum(x => x.venda_valor)
}).ToList();
var jsonResult = new
{
Nomes = resultado.Select(x => x.vendedor_nome),
Valores = resultado.Select(x => x.venda_valor)
};
return Json(resultado);
}catch(Exception)
{
return null;
}
}
And this is where the chart is created, the method is called and it is suposed to fill the chart with the database's return data:
<script>
$(function () {
$.ajax({
url: '/Vendedores/ChartVendedores',
type: 'post',
async: false,
sucess: function (data) {
//Constrói o gráfico com os valores retornados pelo banco.
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Venda dos Colaboradores'
},
xAxis: {
categories: [
data.Nomes
],
crosshair: true
},
yAxis: {
min: 0,
title: {
text: 'Valor (R$)'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Valores',
data: data.Valores
}]
});
}
})
})
What am I'm missing? As long as code goes, i don't think I wrote any wrong code in the method. Am I calling it wrong? Am I manipulating it wrong? I tried to remove my Ajax code, only leaving the chart itself as it is on the highchart.com and it worked, so the problem is not on my container div or in the chart code.
EDIT: As commented bellow, I looked at my console and I'm getting an warning about one of the imports that Highcharts needs. The waning follows is this one. After seeing this, I tried to remove the AJax and only using the highchart code. It worked! For some reason when the chart tries to use this:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
It does not find it when the chart code is contained inside sucess: function(data){}
Note: I'm importing everything at the beggining of the code, meanwhile the script containing the Ajax is written last.
$.ajax({
url: '/Vendedores/ChartVendedores',
type: 'post',
async: false,
sucess: function (data) {
should be changed to:
$.ajax({
url: '/Vendedores/ChartVendedores',
type: 'post',
async: false,
success: function (data) {
You have misspelt success.
look at this, you are using return(resultado), but your json object to be returned is jsonResult , so use this:
var resultado = (from ve in db.tblVendedor
join vn in db.tblVenda on ve.vendedor_id equals vn.vendedor_id
group vn by new
{
ve.vendedor_nome
}into g
select new {
vendedor_nome = g.Key.vendedor_nome,
venda_valor = g.Sum(x => x.venda_valor)
}).ToList();
var jsonResult = new
{
Nomes = resultado.Select(x => x.vendedor_nome),
Valores = resultado.Select(x => x.venda_valor)
};
return Json(jsonResult);
Please test and let me know if it works :)
for (var i in data) {
// Add some text to the new cells:
cell1.innerHTML = data[i].Nomes ;
cell2.innerHTML = data[i].Valores ;
}

Sql Table values in JSON c#

Hi i have a table with following values
Country Count
China 2
India 3
Pakistan 3
i want these in JSON as "China" : 2,"India" : 3,"Pakistan" : 3
I don't want the header Count and Country. I Have tried using ajax and HTTP Handler but no avail
$(document).ready(function () {
$.ajax({
url: 'CountryRegistrations.ashx',
type: 'POST',
dataType: 'json',
success: function (data) {
var test = data.Country + data.Count;
alert(test);
},
error: function (data) {
alert("Error");
}
});
});
public void ProcessRequest(HttpContext context)
{
FilterCountry emp = getCounts();
// serialize and send..
JavaScriptSerializer serializer = new JavaScriptSerializer();
StringBuilder sbJsonResults = new StringBuilder();
serializer.Serialize(emp, sbJsonResults);
context.Response.Clear();
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.Write(sbJsonResults.ToString());
}
private FilterCountry getCounts()
{
FilterCountry fc = new FilterCountry();
fc.Country = "PK";
fc.Count = 600;
return fc;
}
I gives me as PK600 but it should give "PK":600 and how to get these values from database right now im trying to get from hard coded values.
var test = data.Country + data.Count;
Try to change to:
var test = data.Country + ':' + data.Count;
If you are using JavaScriptSerializer then it will will serialize the object in to JSon format like "Key":"Value" that is also based on the object you are passing to Serialize method.
Your class "FilterCountry" has two property "Country" and "Count" and assigning values on it.
So it will be serialize like as follows { "Country" : "PK", "Count":600 }
Please go through JSon and serialize examples

Correcting JSON result object

I have a controller action like this:
List<string> abcd = new List<string>()
foreach (var i in images)
{
abcd.Add("{url:'"+GetImageUrl(i)+"'}");
}
return Json(abcd, JsonRequestBehavior.AllowGet);
So the output of abcd is
["{url:'/PropertyImage/GetPropertyImage?imageId=1'}", "{url:'/PropertyImage/GetPropertyImage?imageId=2'}", "{url:'/PropertyImage/GetPropertyImage?imageId=8'}"]
But the result I want is:
images:[{url:'/PropertyImage/GetPropertyImage?imageId=1'}, {url:'/PropertyImage/GetPropertyImage?imageId=2'}, {url:'/PropertyImage/GetPropertyImage?imageId=8'}]
In my JavaScript, I have
$.ajax({
type: "GET",
url: url,
success: function (result) {
console.log(JSON.stringify(result));
var data = {
images: [result]
};
template = "{{#images}}<a href='{{url}}'><img class='imageborder' src='{{url}}' style='width:150px;height:150px'></img></a>{{/images}}";
renderedOutput= Mustache.to_html(template,data);
$('#Propertyimagelinks').html(renderedOutput);
}
});
How can I get the correct output?
Rather than trying to manually manipulate JSON strings, it seems a lot simpler to use ASP.NET MVC's built in JSON serialization functionality and a little bit of Linq, like this:
var abcd = images.Select(i => new { url = GetImageUrl(i) }).ToList();
return Json(abcd, JsonRequestBehavior.AllowGet);
And in your JavaScript result handler, use this:
var data = { images: result };
Alternatively you can use this in your controller:
var abcd = images.Select(i => new { url = GetImageUrl(i) }).ToList();
return Json(new { images = abcd }, JsonRequestBehavior.AllowGet);
And in your JavaScript:
var data = result;

C# method to return two values from SQL Query, then get via jquery ajax call

UPDATE: This code now works! Between the answer below and my dev who emailed me from Romania, I got it sorted out.
[Method]
public object ConvDetails(string SENDERNAME, string VIEWURL)
{
{
var list = new List<object>();
new Command("select top 1 o.name [SENDERNAME], view_url [VIEWURL] from MESSAGE m join OPR_SECD o on UPDATED_BY = O.RECNUM where VIEW_URL like 'conversation.aspx%' and DELIVER_TO in (select OPR_INITIAL from OPR_SECD where recnum = #CURRENT_USER_ID) order by m.RECNUM desc")
.AddInt("CURRENT_USER_ID", Common.UserID)
.Each(R => list.Add(new
{
VIEWURL = R.GetString("VIEWURL"),
SENDERNAME = R.GetString("SENDERNAME")
}));
return list;
};
}
Here's my ajax call to get the two strings from my method:
convDetails: function() {
$.ajax({
url: BASE_URL + "pages/services/messages.ashx?method=convdetails",
dataType: "json",
async: true,
data: {},
success: function(data) {
$("a.new-message-alert").attr("href", '' + data[0].VIEWURL);
$("span#message-from").text("New Message From: " + data[0].SENDERNAME);
}
});
}
UPDATE:
Between the response I got below and a few emails to our developer who's in Romania, I was able to piece it together. I updated my code to what worked! The having just data.VIEWURL didn't work. I had to add the data[0].VIEWURL. So, thanks Matt for that one. Also, in my href i had to put in empty quotes or it would return NaN. No idea why.
Thanks!
Well, that JavaScript isn't going to work whatever you do on the C# side. You're attempting synchronous processing of the result of an asynchronous call.
Your C# doesn't look far off, for some reason I totally failed to read it correctly first time around. I've never used a .ashx in quite that manner, I've always just spat out my response from ProcessRequest, but if your code is getting called then I just learned something new. I do, however, notice that you're returning a serialized list, but only processing one element.
You could use a more LINQy approach to eliminate the explicit list filling, though:
var list =
from R in new Command("select top 1 o.name [SENDERNAME], view_url [VIEWURL] from MESSAGE m join OPR_SECD o on UPDATED_BY = O.RECNUM where VIEW_URL like 'conversation.aspx%' and DELIVER_TO in (select OPR_INITIAL from OPR_SECD where recnum = #CURRENT_USER_ID) order by m.RECNUM desc")
.AddInt("CURRENT_USER_ID", Common.UserID)
select new {
VIEWURL = R.GetString("VIEWURL"),
SENDERNAME = R.GetString("SENDERNAME") };
context.Response.Write(JsonConverter.SeralizeObject(list));
Your JS should look more like:
convDetails: function() {
$.ajax({
url: BASE_URL + "pages/services/messages.ashx?method=convdetails",
async: true,
data: {},
success: function(data) {
$("a.new-message-alert").attr("href", data[0].VIEWURL);
$("a.new-message-alert").text("New message from: " + data[0].SENDERNAME);
}
});
}

Categories

Resources