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
""iVBORw0KGgoAAAANSUhEUgAAAkQAAAJECAYAAAD34DtaAA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uTXaMK3RRv2uNdowrdHGk1ujDVOcblCiR2lao40nt0YbpjXaqN+1RhumNdp4cmu0YYrTDUr0KE1rtPHk1mjDtEYb9bvWaMO0RhtPbo02THG6QYkepWmNNp7cGm2Y1mijftcabZjWaOPJrdGGKU43KNGjNK3RxpNbow3TGm3U71qjDdMabTy5NdowxekGJXqUpjXaeHJrtGFao436XWu0YVqjjSe3RhumON2gRI/StEYbT26NNkxrtFG/a402TGu08eTWaMMUpxuU6FGa1mjjya3RhmmNNup3rdGGaY02ntwabZjidIMSPUrTGm08uTXaMK3RRv2uNdowrdHGk1ujDVOcblCiR2lao40nt0YbpjXaqN+1RhumNdp4cmu0YYrTDUr0KE1rtPHk1mjDtEYb9bvWaMO0RhtPbo02THG6QYkepWmNNp7cGm2Y1mijftcabZjWaOPJrdGGKU43KNGjNK3RxpNbow3TGm3U71qjDdMabTy5NdowxekGJXqUpjXaeHJrtGFao436XWu0YVqjjSe3RhumON2gRI/StEYbT26NNkxrtFG/a402TGu08eTWaMMUpxuU6FGa1mjjya3RhmmNNup3rdGGaY02ntwabZjidIMSPUrTGm08uTXaMK3RRv2uNdowrdHGk1ujDVOcblCiR2lao40nt0YbpjXaMK3RhmmNNkxrtGFao40nt0YbpjjdoESP0rRGG09ujTZMa7RhWqMN0xptmNZow7RGG09ujTZMcbpBiR6laY02ntwabZjWaMO0RhumNdowrdGGaY02ntwabZjidIMSPUrTGm08uTXaMK3RhmmNNkxrtGFaow3TGm08uTXaMMXpBiV6lKY12nhya7RhWqMN0xptmNZow7RGG6Y12nhya7RhitMNSvQoTWu08eTWaMO0RhumNdowrdGGaY02TGu08eTWaMMUpxuU6FGa1mjjya3RhmmNNkxrtGFaow3TGm2Y1mjjya3RhilONyjRozSt0caTW6MN0xptmNZow7RGG6Y12jCt0caTW6MNU5xuUKJHaVqjjSe3RhumNdowrdGGaY02TGu0YVqjjSe3RhumON2gRI/StEYbT26NNkxrtGFaow3TGm2Y1mjDtEYbT26NNkxxukGJHqVpjTae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SPrOk6OrPpOjpzPafc0hdJ/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);
Related
First of all- I know I should use HTTP POST and I know how to do it.
But my task is to use HTTP GET anyway. Now, there's a problem. I have a WebMethod:
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json,UseHttpGet =true)]
public List<string> AddToCollection(string name, string lastname)
{
collection.Add(name + " " + lastname);
return collection;
}
Now, code from .js :
function AddToArray() {
var name = document.getElementById("name_add").value;
var lastname = document.getElementById("surname_add").value;
if (name == "" || lastname == "") {
alert("Wrong!");
} else {
var dataT = JSON.stringify({"name":name,"lastname":lastname});
$.ajax({
type: "GET",
url: "http://localhost:45250/ServiceJava.asmx/AddToCollection",
data: dataT,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
}
Now the thing is: it works perfect when I use type POST. But with GET I get the error that the parameter name cannot be recognized. What should I change to make it work?
Hi i am trying to call a C# method to return a json but keep getting errors.
$.ajax({
type: 'POST',
url: 'ReportList.aspx/GetReports',
dataType: 'json',
success: function (response) {
dataset = response.d;
},
error: function (response, success, error) {
alert("Error: " + error);
}
});
The error i am getting reads as:
Unexpected token <
Previously i had contentType: 'application/json; charset=utf-8', added but that returned a internal server error.
I would like to call json so that i may populate a javascript.datatable.
C# Function:
public string GetReports()
{
System.Data.DataSet d;
d = (System.Data.DataSet)Session["dsHistory"];
System.Data.DataSet DsNew = new System.Data.DataSet("cdreports");
System.Data.DataTable table1 = new System.Data.DataTable("reports");
table1.Columns.Add("id");
table1.Columns.Add("name");
table1.Columns.Add("regAndId");
table1.Columns.Add("type");
table1.Columns.Add("timeStamp");
foreach (System.Data.DataRow row in d.Tables["company"].Rows)
{
table1.Rows.Add(row["rc_id"], row["companyname"], row["companyregnumber"], "Company", row["rc_timestamp"]);
}
foreach (System.Data.DataRow row in d.Tables["director"].Rows)
{
table1.Rows.Add(row["rd_id"], row["firstname"] + " " + row["surname"], row["idnumber"], "Director", row["rd_timestamp"]);
}
DsNew.Tables.Add(table1);
string json = JsonConvert.SerializeObject(DsNew, new DataSetConverter());
return json;
}
Make sure trace is disabled on the page. Sometimes ajax calls don't work if page tracing is enabled.
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)
{
}
could you please help with this. I have the following javascript:
$('form').click(function (e)
{
if (e.target.getAttribute('id') === 'SubmitAddLevel')
{
var parent = $('#' + e.target.getAttribute('attr')),
var Data = [];
parent.find('.input').children().each(function (i, e)
{
Data.push(e.getAttribute('id') + ":" + e.value);
console.log(Data);
});
$.ajax({
type: "POST",
url: 'AjaxControls.aspx/CreateUserLevel',
//data: Data, //.join(','),
dataType: "text",
contentType: "application/json; charset=utf-8",
//error: function (er) { alert(er); },
success: function (response)
{
if (response.d === "true")
{
$("#ErrorDivAddLevel").html('Level created successfully!').fadeIn('slow');
}
else
{
$("#SuccessDivAddLevel").html('Level creation failed!').fadeIn('slow');
}
},
});
}
The result of 'Data' I got on the console is :["LevelNameAddLevel:Admin", "PriviledgeIDAddLevels:|1|2|3|4|5|6|7|"]. How do I convert this to what ajax will pass to my web menthod?
Here is the web method
<WebMethod(EnableSession:=True)>
Public Shared Function CreateUserLevel(userLevel As String, userPriviledges As String) As String
return "true"
end function
I think your Data should look something more like this:
[{"LevelNameAddLevel":"Admin"}, {"PriviledgeIDAddLevels":"|1|2|3|4|5|6|7|"}]
So you have key / value pairs inside of an array. In the request, you should then be able to fetch the data via the keys in the request.
But I'm not quite sure what this is supposed to mean : "|1|2|3|4|5|6|7|"
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) + "'}"