I have some problem ajax with query string, I can send the data if page does not have and Info.aspx/Save works great. But when I fill somethings with query string then post same data it will return http 500 error. I have nothing with querystring in javascript I use it in C# for id.
var data = '{name: "' + $("input[name$='name']").val() +
'",description: "' + $("input[name$='description']").val() +
'",code: "' + $("input[name$='code']").val() +'"}';
$.ajax({
type: "POST",
url: "Info.aspx/Save",
data: data,
contentType: "application/json",
dataType: "json",
success: function (data) {
var result = data.d
console.log(result)
if (result > 0)
success.show();
else
error.show();
Metronic.scrollTo(error, -200);
},
error: function () {
console.log('err')
}
});
[WebMethod]
public static int Save(string name, string description, string code)
{
ClassInfo classInfo = new ClassInfo();
return ClassInfo.Save(name, code, description, FileInfo.id);
}
I just use querystring in C# for filling inputs. Altough I send same data it works without querystring inpgae's adressbar, If it has querystring in addressbar ajax returns me http500 error and Save WebMethod does not work.
data types must be object, no string.
var data = {name: $("input[name$='name']").val() ,description:$("input[name$='description']").val(),code:$("input[name$='code']").val()};
Remove the contentType or change it to
"application/x-www-form-urlencoded; charset=utf-8"
Then
$.post('/Info.aspx/Save',data ,
function (data) {
});
Or
$.ajax({
url: '/Info.aspx/Save',
data: data
});
Server side
Your json parameter names must be same with the c# paramter names.
[WebMethod(true)]
public static string Save(string name, string description, string code)
{
return name+" "+description+" "+code;
}
Usable for Web Method and Query String(working for both)
The query string parameters need to be passed as JSON.
data: JSON.stringify({ "name": "name", "description": "description","code":"code" }),
contentType: "application/json; charset=utf-8"
Server side
[WebMethod(true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static String Save(string name, string description, string code)
{
}
Related
I'm using VS2022 with C# and I'm trying to use an $ajax get method in my JavaScript function. I'm sending a parameter and returning a string[] list but when I receive the return I use JSON.stringify but when I try to use JSON.Parse it fails. The Javascript code is
$.ajax({
type: "GET",
url: '/Home/GetCategories/',
contentType: 'application/json',
datatype: 'json',
data: { ctgData: JSON.stringify(relvalue)}
}).done(function(result) {
let userObj = JSON.stringify(result);
let resultList = JSON.parse(userObj);
});
The code in the controller which returns the list is simple at the moment until I get the return working
[HttpGet]
public ActionResult GetCategories(string ctgData)
{
string[] categoryList = { "Food & Drink", "Sport & Fitness", "Education", "Housework", "Fiction", "Horror Books", "Fantasy", "Magic" };
return Json(new { data = categoryList });
}
The value in result is
{"data":["Food & Drink","Sport & Fitness","Education","Housework","Fiction","Horror Books","Fantasy","Magic"]}
I've tried a number of different ways in Parse but it always fails, can you tell me what I'm missing to get my resultList to contain the string array.
You don' t need to parse anything. It is already java script object
$.ajax({
type: "GET",
url: '/Home/GetCategories/',
contentType: 'application/json',
datatype: 'json',
data: { ctgData: JSON.stringify(relvalue)}
sucess: function(result) {
let data=result.data; // data = ["Food & Drink","Sport & Fitness",..]
}
});
use this:
JSON.parse(JSON.stringify(data))
const data = {"data":["Food & Drink","Sport & Fitness","Education","Housework","Fiction","Horror Books","Fantasy","Magic"]}
const resultJSON = JSON.parse(JSON.stringify(data))
console.log("json >>>", resultJSON)
I want to create QR Code from user data. I have using below library for creating QR Code.
Install-Package QRCoder
Now I have done below code to convert data into base64 string.
private static Byte[] BitmapToBytes(Bitmap img)
{
using (MemoryStream stream = new MemoryStream())
{
img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
return stream.ToArray();
}
}
public JsonResult SaveVisitorEntry(string FirstName, string LastName)
{
//VisitorEntryDA pdm = new VisitorEntryDA();
object obj = "";//pdm.getCity(country_id, Convert.ToInt64(state_id));
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeData qrCodeData = qrGenerator.CreateQrCode(FirstName + " " + LastName, QRCodeGenerator.ECCLevel.Q);
QRCode qrCode = new QRCode(qrCodeData);
Bitmap qrCodeImage = qrCode.GetGraphic(20);
ImageConverter converter = new ImageConverter();
return Json(JsonConvert.SerializeObject(BitmapToBytes(qrCodeImage)));
}
Below is my AJAX code where i am converting Base64 to image and showing my QR code to image.
jQuery.ajax({
url: "../VisitorEntry/SaveVisitorEntry",
type: "POST",
//data: "{function:'" + value + "'}",
data: "{FirstName:'" + FirstName + "',LastName:'" + LastName + "'}",
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
debugger
jQuery("#wait").css("display", "none");
toastr['success']('Line Stoppage closed Successfully');
//var results = JSON.parse(data);
//if (results.length == 0) {
// jQuery("#wait").css("display", "none");
//} else {
// f_group_data = results.Table;
// bindDropDown("function_name", f_group_data, "FUNCTION", "FUNCTION", "Select");
// jQuery('#function_name').chosen();
// jQuery('#function_name').trigger("chosen:updated");
// jQuery("#wait").css("display", "none");
//}
QrCodeImage.setAttribute('src', "data:image/jpg;base64," + data);
//setTimeout(function () {// wait for 5 secs(2)
// location.reload(); // then reload the page.(3)
//}, 3000);
},
error: function (data) {
jQuery("#wait").css("display", "none");
console.log("error");
}
});
I am not getting correct formate of base64 string and getting below error in console.
Failed to load resource: net::ERR_INVALID_URL
Below value I am getting in data variable
""iVBORw0KGgoAAAANSUhEUgAAAkQAAAJECAYAAAD34DtaAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAC5MSURBVHhe7dZRiiNLFgTRt/9Nz2zABGrMQbcy7YB9exAZ1a3//pckSfJy/SBKkiSv1w+iJEnyev0gSpIkr9cPoiRJ8nr9IEqSJK/XD6IkSfJ6/SBKkiSv1w+iJEnyev0gSpIkr9cPoiRJ8nr9IEqSJK/XD6IkSfJ6/SBKkiSv1w+iJEnyev0gSpIkr9cPoiRJ8nr9IEqSJK/XD6IkSfJ6/SBKkiSv1w+iJEnyev0gSpIkr9cPoiRJ8nr9IEqSJK/XD6IkSfJ6/SBKkiSv1w+iJEnyev0gSpIkr9cPoiRJ8nr9IEqSJK/XD6IkSfJ6/SBKkiSv1w+iJEnyev0gSpIkr9cPoiRJ8nr9IEqSJK/XD6IkSfJ6/SBKkiSv1w+iJEnyev0gSpIkr9cPoiRJ8nr9IEqSJK/XD6IkSfJ6/SBKkiSv1w+iJEnyev0gSpIkr9cPoiRJ8nr9IEqSJ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KUW+gbmdZoo37XGm2Ycgt9I1OcblCiR2nKLfSNTGu0Ub9rjTZMuYW+kSlONyjRozTlFvpGpjXaqN+1Rhum3ELfyBSnG5ToUZpyC30j0xpt1O9aow1TbqFvZIrTDUr0KE25hb6RaY026net0YYpt9A3MsXpBiV6lKbcQt/ItEYb9bvWaMOUW+gbmeJ0gxI9SlNuoW9kWqON+l1rtGHKLfSNTHG6QYkepSm30DcyrdFG/a412jDlFvpGpjjdoESP0pRb6BuZ1mijftcabZhyC30jU5xuUKJHacot9I1Ma7RRv2uNNky5hb6RKU43KNGjNOUW+kamNdqo37VGG6bcQt/IFKcblOhRmnILfSPTGm3U71qjDVNuoW9kitMNSvQoTbmFvpFpjTbqd63Rhim30DcyxekGJXqUpjXaeHJrtGFao436XWu0YVqjjSe3RhumON2gRI/StEYbT26NNkxrtFG/a402TGu08eTWaMMUpxuU6FGa1mjjya3RhmmNNup3rdGGaY02ntwabZjidIMSPUrTGm08uTXaMK3RRv2uNdowrdHGk1ujDVOcblCiR2lao40nt0YbpjXaqN+1RhumNdp4cmu0YYrTDUr0KE1rtPHk1mjDtEYb9bvWaMO0RhtPbo02THG6QYkepWmNNp7cGm2Y1mijftcabZjWaOPJrdGGKU43KNGjNK3RxpNbow3TGm3U71qjDdMabTy5NdowxekGJXqUpjXaeHJrtGFao436XWu0YVqjjSe3RhumON2gRI/StEYbT26NNkxrtFG/a402TGu08eTWaMMUpxuU6FGa1mjjya3RhmmNNup3rdGGaY02ntwabZjidIMSPUrTGm08uTXaMK3RRv2uNdowrdHGk1ujDVOcblCiR2lao40nt0YbpjXaqN+1RhumNdp4cmu0YYrTDUr0KE1rtPHk1mjDtEYb9bvWaMO0RhtPbo02THG6QYkepWmNNp7cGm2Y1mijftcabZjWaOPJrdGGKU43KNGjNK3RxpNbow3TGm3U71qjDdMabTy5NdowxekGJXqUpjXaeHJrtGFao436XWu0YVqjjSe3RhumON2gRI/StEYbT26NNkxrtFG/a402TGu08eTWaMMUpxuU6FGa1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djWqONS63RxqXehu7AlPwLekOm3NIXOYb+aExrtHGpNdq41NvQHZiSf0FvyJRb+iLH0B+NaY02LrVGG5d6G7oDU/Iv6A2Zcktf5Bj6ozGt0cal1mjjUm9Dd2BK/gW9IVNu6YscQ380pjXauNQabVzqbegOTMm/oDdkyi19kWPoj8a0RhuXWqONS70N3YEp+Rf0hky5pS9yDP3RmNZo41JrtHGpt6E7MCX/gt6QKbf0RY6hPxrTGm1cao02LvU2dAem5F/QGzLllr7IMfRHY1qjjUut0cal3obuwJT8C3pDptzSFzmG/mhMa7RxqTXauNTb0B2Ykn9Bb8iUW/oix9AfjWmNNi61RhuXehu6A1PyL+gNmXJLX+QY+qMxrdHGpdZo41JvQ3dgSv4FvSFTbumLHEN/NKY12rjUGm1c6m3oDkzJv6A3ZMotfZHkD6N/ZE3X0ZlN19GZ6znllr5I8ofRP7Km6+jMpuvozPWccktfJPnD6B9Z03V0ZtN1dOZ6TrmlL5L8YfSPrOk6OrPpOjpzPafc0hdJ/jD6R9Z0HZ3ZdB2duZ5TbumLJH8Y/SNruo7ObLqOzlzPKbf0RZI/jP6RNV1HZzZdR2eu55Rb+iLJH0b/yJquozObrqMz13PKLX2R5A+jf2RN19GZTdfRmes55Za+SPKH0T+ypu…"
The base64 value you provided in your question is malformed, my recommendation is to not use Json Serialization for this Api response effort.
Try using Convert.ToBase64String
Ensure the method returns string
and the jQuery request accepts/expects text for dataType
response.
Diff in your Api Endpoint
public IActionResult SaveVisitorEntry(string FirstName, string LastName)
{
...
return Ok(Convert.ToBase64String(BitmapToBytes(qrCodeImage)));
}
Diff in your request
jQuery.ajax({
dataType: "text",
success: function (data) {
QrCodeImage.setAttribute('src', "data:image/jpg;base64," + data);
}
});
Edit
Correction on contentType, shoul be dataType that is changed to handle response of request.
Additionally,
Though I'm not certain this is related to the issue you're observing here, I do think the data request payload should be an object, not a string.
...
type: "POST",
data: {
FirstName: FirstName,
LastName: LastName
},
dataType: "text",
...
You should also consider handling scenarios where both Firstname and Lastname parameter are null, whitespace or string.Empty in your Api endpoint.
I would also string.Trim() here as a sanity effort: qrGenerator.CreateQrCode($"{FirstName} {LastName}".Trim(), QRCodeGenerator.ECCLevel.Q);
I have this method to send some data with ajax:
function SendData(foodID, basketID) {
var data = { FoodID: foodID, BasketID: basketID };
$.ajax({
url: '/Order/Post',
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json;utf-8',
datatype: 'json'
}).done(function (data) {
console.log(data);
}).fail(function (data) {
console.log("Error: " + data);
});
}
In C#, my Post Method in my Order controller gets triggered, but the string I want to hand over is null:
public bool Post(string s)
{
//When this gets executed, s is null
return true;
}
I tested this by executing SendData(1,1) directly on a button click. What is the mistake I'm doing and how can I get the string in my Post-Method?
you are post the object. not string.
you can try generate to object and load this object. or add new one parameter to action (foodId and basketId but you must post like that if you check this option data:{foodId,basketId})
//model
public class SomeObject{
public string FoodId {get;set;}
public string BasketId {get;set;}
}
//code
public bool Post(SomeObject data)
{
return true;
}
It seems for me your data structure to the Post action doesn't match action parameter names. Try this:
[HttpPost]
public bool Post(string foodID, string baskedID)
{
return true;
}
I believe you have to name your data that's being passed like so:
data: { 's': JSON.stringify(data) }
I have such JSON string:
'{"1":[1,3,5],"2":[2,5,6],"3":[5,6,8]}'
I want to send it to the Web Api Controller without changing using ajax request:
$.ajax({
type: "POST",
url: "Api/Serialize/Dict",
data: JSON.stringify(sendedData),
dataType: "json"
});
In Web Api I have such method:
[HttpPost]
public object Dict(Dictionary<int, List<int>> sendedData)
{
//code goes here
return null;
}
And always sendedData == null. Another words: I don't know how to deserialize JSON into (Dictionary<int, List<int>>.
Thank you for answer.
Try this
[HttpPost]
public object Dict(Dictionary<int, List<int>> sendedData)
{
var d1 = Request.Content.ReadAsStreamAsync().Result;
var rawJson = new StreamReader(d1).ReadToEnd();
sendedData=Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<int, List<string>>>(rawJson);
}
You can send the data like this:
{"sendedData":[{"key":"1","value":[1,3,5]},{"key":"2","value":[2,5,6]},{"key":"3","value":[5,6,8]}]}
Image of the function in the controller:
Dict
Try it:
Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<int, List<string>>>("{'1':[1,3,5],'2':[2,5,6],'3':[5,6,8]}");
Try using:
public ActionResult Parse(string text)
{
Dictionary<int, List<int>> dictionary = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<int, List<int>>>(text);
return Json(dictionary.ToString(), JsonRequestBehavior.AllowGet);
}
This works when the sent data doesn't have quotes around the indices:
{1:[1,3,5],2:[2,5,6],3:[5,6,8]}
Also make sure that you send an object in the Javascript:
data: {
text: JSON.stringify(sendedData)
},
specify the content type parameter when performing ajax call, dataType is for return result:
$.ajax({
type: "POST",
url: "Api/Serialize/Dict",
contentType: "application/json; charset=utf-8", //!
data: JSON.stringify(sendedData)
});
You missed the [FromBody] annotation in the sendedData param. Try this:
[HttpPost]
[Consumes("application/json")]
[Produces("application/json")]
public object Dict([FromBody] Dictionary<int, List<int>> sendedData)
{
//code goes here
return null;
}
I am posting a JSON string to asp.net MVC as follows.
AJAX call
$.ajax({
type: "POST",
url: "#(storeLocation)IDR/OpcInsertCustomerProfile/",
data: JSON.stringify(currSelection),
contentType: "application/json",
success: function(data) {
alert('success : ' + JSON.stringify(data));
},
error: function(data) {
alert('Error : ' + JSON.stringify(data));
}
}
);
In the controller:
[HttpPost]
[ActionName("OpcInsertCustomerProfile")]
public JsonResult OpcInsertCustomerProfile(string currSelectionData)
{
try
{
JavaScriptSerializer ser = new JavaScriptSerializer();
var res = ser.Serialize(currSelectionData);
return Json(currSelectionData, JsonRequestBehavior.AllowGet);
}
catch (Exception exc)
{
return Json(new { error = 1, message = exc.Message });
}
}
Debugger indicates the action gets called successfully, however the incoming string parameter being received is always null. Firebug 'post' shows outgoing parameter is proper json object. I am expecting to see the JSON string as incoming parameter. Please note that I don't want to de-serialise it into proper object. All I want to do is store the string in JSON format 'as-it-is' in a database. Later on it needs be retrieved ans passed to Javascript as it is.
Try this :
$.ajax({
type: "POST",
url: "#(storeLocation)IDR/OpcInsertCustomerProfile/",
data: { "currSelectionData" : "'" + JSON.stringify(currSelection) + "'" },
contentType: "application/json",
success: function(data) {
alert('success : ' + JSON.stringify(data));
},
error: function(data) {
alert('Error : ' + JSON.stringify(data));
}
}
);
One way is to allow the action to receive the parameter as POST data instead of JSON "Stringified" data. To do that, post the data without JSON.Stringify. Hopefully this is what you need.
If not you might want to try creating an object just to receive this simple data.
Look at your action method: is it correct that method accepts string with serialized JSON, than serialized that string as JSON again and then dismiss the result and serializes and returns the same string again?
If you send request with application/json type ASP.NET MVC tries to deserialize received string and bind it to action parameters: in your case it tries to find property currSelectionData inside your JSON object. Is that property exists? Maybe you expect whole string is received as currSelectionData parameter? Then you need to use FormCollection or Request.Form instead because default model binder does not support this.
Actually i fill my state dropdown in selection of country with json i do like this
in my controller i have action it's return my data in json format like this it's below
public JsonResult State(int countryId)
{
var stateList = CityRepository.GetList(countryId);
return Json(stateList, JsonRequestBehavior.AllowGet);
}
in my view
<script type="text/javascript">
function cascadingdropdown() {
$("#stateID").empty();
$("#stateID").append("<option value='0'>--Select State--</option>");
var countryID = $('#countryID').val();
$.ajax({
url: "/City/State",
dataType: 'json',
data: { countryId: countryID },
success: function (data) {
$("#stateID").empty();
$("#stateID").append("<option value='0'>--Select State--</option>");
$.each(data, function (index, optiondata) {
alert(optiondata.StateName);
$("#stateID").append("<option value='" + optiondata.ID + "'>" + optiondata.StateName + "</option>");
});
},
error: function () {
alert('Faild To Retrieve states.');
}
});
}
</script>
i think this will help you...
When sending json through Ajax, I think this is the right approach for the data property in Ajax:
data: "{'parameterNameInAction':'" + JSON.stringify(jsonData) + "'}"