Sending value in ajax call and reading it in page load - c#

I'm making an ajax call in the function as below
function UploadPic() {
debugger;
// generate the image data
var canvas = document.getElementById("canvas");
var dataURL = canvas.toDataURL("image/png");
// Sending the image data to Server
$.ajax({
type: 'POST',
url: "baseimg.aspx",
data: { imgBase64: dataURL },
success: function () {
alert("Done, Picture Uploaded.");
window.opener.location.reload(true); // reloading Parent page
window.close();
window.opener.setVal(1);
return false;
}
});
}
And in the page load I'm trying to get the value as
protected void Page_Load(object sender, EventArgs e)
{
StreamReader reader = new StreamReader(Request.InputStream);
string Data = Server.UrlDecode(reader.ReadToEnd());
reader.Close();
}
In the dataURL I'm getting the value but in the page load 'string Data' is coming as empty.
I have referred to Capturing Image From Web Cam in ASP.Net to make this functionality.
The ajax is hitting successfully to the code then coming back and executing the success portion in the ajax call.
I'm finding no way out of it.

Since it is a POST operation, try checking the form variable like the following for the data string:
Request.Form["imgBase64"]

Related

How to update image returned as File in ASP.NET MVC Controller using Ajax?

I have a base image, and I use C# Graphics library to add data to it, and then return the image converted to byte array.
I have a controller:
public ActionResult DisplayDR(int drNum)
{
ER dr = DataUtility.getDR(drNum, errors);
return File(DrawDRUtility.getDRimageAsByteArray(dr), "image/png");
}
That works fine with,
<img id="drImage" src="#Url.Action("DisplayDR")" width="1110" height="484" alt="qr code" />
I need to be able to dynamically update the image and attempted with ajax with no luck.
Using:
function getNewDRImage(instance) {
var drNum = $(instance).data('val');
var src = '#Url.Action("DisplayDR", "Home", new { area = "Part" })';
$.ajax({
type: "GET",
url: src,
data: { drNum : drNum },
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (err) {
var msg = "Client side error, " + err;
throwClientSideErrorMsg(msg)
},
success: function (data) {
$('#drImage').attr("src", data.image);
}
});
}
and returning JSON like so,
public JsonResult DisplayDMR(int drNum)
{
ER dr = DataUtility.getDR(drNum, errors);
return
Json(new { image = File(DrawDRUtility.getDRimageAsByteArray(dr), "image/png") }, JsonRequestBehavior.AllowGet);
}
Gives me this error:
System.Web.HttpException (0x80004005): The controller for path '/[object Object]' was not found or does not implement IController.
What am I not doing correctly?
update, viewing the source after the ajax call I see why the error occurs, as this is what the response is:
<img id="dmrImage" src="[object Object]" alt="qr code" height="484" width="1110">
So I guess I am confused on what to do with the JSON data to update the image.
With your ajax code you're trying to load actual bytes of your image and assign that to the src attribute. That's not what the attribute expects.
All you need is to just assign a new image url as a string. The browser then will automatically fetch actual bytes and show the new image for you.
If you want to use the same url for the updated image you need to make sure the browser won't use your old cached image. Take a look at this answer for how to do this.
To add Cache-Control: header to your File() response use Response.AddHeader() method:
public ActionResult DisplayDR(int drNum)
{
Response.AddHeader("Cache-Control", "no-store");
ER dr = DataUtility.getDR(drNum, errors);
return File(DrawDRUtility.getDRimageAsByteArray(dr), "image/png");
}

How to obtain checked checkbox values on the serverside in c# from an ajax Http POST using web forms (not MVC)?

Here's my ajax call:
$(function () {
$("#chkFilter").on("click", "input", function (e)
{
var filterCheckboxes = new Array();
$("#chkFilter").find("input:checked").each(function () {
//console.log($(this).val()); //works fine
filterCheckboxes.push($(this).prop("name") + "=" + $(this).val());
console.log($(this).prop("name") + "=" + $(this).val());
//var filterCheckboxes = new Array();
//for (var i = 0; i < e.length; i++) {
// if (e[i].checked)
// filterCheckboxes.push(e[i].value);
//}
});
console.log("calling ajax");
$.ajax({
url: "/tools/oppy/Default",
type: "POST",
dataType: "json",
data: { filterValues: filterCheckboxes }, // using the parameter name
success: function (result) {
if (result.success) {
}
else {
}
}
});
});
});
And my server side code:
public partial class tools_oppy_Default : System.Web.UI.Page
{
...
protected void Page_Load(object sender, EventArgs e)
{
if (Request.HttpMethod == "POST")
{
string checkedBoxes = Request["filterValues"];
testLabel.Text = checkedBoxes;
}
I'm just trying to obtain the post URL with the appropriate checked values so I can parse it on the server. However, I'm having trouble obtaining the URL. The string checkedBoxes is supposed to hold a query string like name=value&name=value&name.... but when I test it, the testLabel doesn't show anything. I'm using web forms app, not MVC. Also, I'm new to ajax and their behavior. Thanks.
First, I assume that the url in you JQuery call is valid as there is not aspx extension their.
Second, It looks like what you need to do is create a web method and call it from JQuery for example the following is a web method that accept string
[WebMethod]
public static string GetData(String input)
{
return DateTime.Now.ToString();
}
and you can call it using the same way with your current code just update the url parameter to include the method name
url: "PageName.aspx/MethodName",
for more details about web methods and their union with JQuery please check this article
Edited The following is complete sample
The web method should look like the following one
[WebMethod]
public static string GetData(string filterValues)
{
return filterValues; //This should be updated to return whatever value you need
}
The client side part of calling the web method should look like the following
$.ajax({
url: "/Default/GetData",
type: "POST",
contentType: "application/json; charset=utf-8", //I have added this as "contentType" parameter represents the type of data inside the request meanwhile the "data" parameter describes the data inside the response
data: "{ filterValues:\"" + filterCheckboxes + "\"}", //Note that I have updated the string here also set the name of the parameter similar to the input of the webmethod
dataType: "json",
success: function (result) {
alert(result.d);//You should access the data using the ".d"
}
});
One last thing, If you are using asp.net permanent routing the above code will not work and you should disable it by updating the file "App_Code/RouteConfig.cs" From
settings.AutoRedirectMode = RedirectMode.Permanent;
To
settings.AutoRedirectMode = RedirectMode.Off;
And remember to clear browser cache after the above update

How to get access drop-down control from static web method

I am trying to get access a drop-down that is in aspx page from static web method but it seems i can't get access and not what am i doing wrong. I want to set the dropdown index value to -1. thanks
this is what i am trying to do:
[System.Web.Services.WebMethod]
public static void Cancel()
{
myDDL.SelectedIndex = -1;
}
here is the javascript call
<script type="text/javascript" language="javascript">
function Func() {
//alert("hello!")
var result = confirm('WARNING');
if (result) {
//click ok button
PageMethods.Delete();
}
else {
//click cancel button
PageMethods.Cancel();
}
}
</script>
I am trying to get access a drop-down that is in aspx page from static web method
the web method in asp.net page are static, this mean are executed without page context(not completely true, you can access to Session), so what you need its retrieve result from web method, then make your update client side, something like(not tested, sorry):
jQuery.ajax({
url: 'callAJAX.aspx/Cancel',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
var result = data.d.result;
$('#yourDropDownID')[0].selectedIndex = result;
}
});
It should be myDDL.selectedIndex = -1;
You cannot access a control inside webmethod..At the web service method level you cannot see anything about the page structure..
You can try this code for clearing dropdown..
Instead of calling pagemethod Cancel you can clear it inside javascript function itself..
var ddl = document.getElementById('myDDL');
ddl.options[ddl.selectedIndex] = 0;
Refer this link for extra reading..

Extjs File Upload with C#

I know how the xtype: filefield works and I also realized that file upload does not use the regular ajax method to read and write data to database...
I can set up filefield normally and when I click the browse button I can select the necessary file.
this.fp = Ext.create('Ext.form.Panel', {
scope: this,
width: 200,
frame: true,
title: 'File Upload Form',
autoHeight: true,
bodyStyle: 'padding: 10px 10px 0 10px;',
items: [
{
xtype: 'filefield'
}
],
buttons: [
{ text: 'Upload',
handler: function () {
var form = this.up('form').getForm();
if (form.isValid()) {
form.submit({
url: 'Upload.aspx',
waitMsg: 'Uploading your file...',
success: function (form, action) {
alert("OK:" + action.result.message);
},
failure: function (form, action) {
alert("Error:" + action.result.message);
}
});
}
}
}
]
});
What happens after the upload button is clicked is the problem... How would I get the file uploaded to server side...(sql db)... using c#
I tried creating an upload.aspx page with upload.aspx.cs and did this just to see if it worked...
public partial class Upload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
if (context.Request.Files.Count > 0)
{
BinaryReader file = new BinaryReader(context.Request.Files[0].InputStream);
string line;
while ((line = file.ReadString()) != null)
{
// sql connection?
}
}
// prepare response
MessageOb result = new MessageOb();
result.success = true;
result.message = "Success";
}
}
But I get this error
Ext.Error: You're trying to decode an invalid JSON String:
Has someone documented where I can see the usual step to upload a file to sql db from extjs on client side and c# on serverside... or I'd really appreciate if someone can show me how it's done
The problem is probably related to how you return data from the upload form submit. Ext.JS requires the response to be JSON or XML, I would verify you are not returning a html document.
I presume MessageOb handles this somehow...maybe?
Uncaught Ext.Error: You're trying to decode an invalid JSON String: Form Submission using Ext JS and Spring MVC

Problem on how to update the DOM but do a check on the data with the code-behind

This is with ASP.NET Web Forms .NET 2.0 -
I have a situation that I am not sure how to fulfill all the requirements. I need to update an img source on the page if selections are made from a drop down on the same page.
Basically, the drop downs are 'options' for the item. If a selection is made (i.e. color: red) then I would update the img for the product to something like (productID_red.jpeg) IF one exists.
The problem is I don't want to do post backs and refresh the page every time a selection is made - especially if I do a check to see if the image exists before I swap out the img src for that product and the file doesn't exist so I just refreshed the entire page for nothing.
QUESTION:
So I have easily thrown some javascript together that formulates a string of the image file name based on the options selected. My question is, what options do I have to do the following:
submit the constructed image name (i.e. productID_red_large.jpg) to some where that will verify the file exists either in C# or if it is even possible in the javascript. I also have to check for different possible file types (i.e. .png, .jpg...etc.).
not do a post back and refresh the entire page
Any suggestions?
submit the constructed image name
(i.e. productID_red_large.jpg) to some
where that will verify the file exists
either in C# or if it is even possible
in the javascript. I also have to
check for different possible file
types (i.e. .png, .jpg...etc.).
not do a post back and refresh the
entire page
If you wish to not post back to the page you will want to look at $.ajax() or $.post() (which is just short hand for $.ajax() with some default options)
To handle that request you could use a Generic Http Handler.
A simple outline could work like the following:
jQuery example for the post:
$("someButton").click(function () {
//Get the image name
var imageToCheck = $("#imgFileName").val();
//construct the data to send to the handler
var dataToSend = {
fileName: imageToCheck
};
$.post("/somePath/ValidateImage.ashx", dataToSend, function (data) {
if (data === "valid") {
//Do something
} else {
//Handle error
}
}, "html");
})
Then on your asp.net side you would create an http handler that will validate that request.
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var fileName = context.Request["fileName"];
var fullPath = Path.Combine("SomeLocalPath", fileName);
//Do something to validate the file
if (File.Exists(fullPath))
{
context.Response.Write("valid");
}
else
{
context.Response.Write("invalid");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
Hope this helps, if I missed the mark at all on this let me know and I can revise.
We have an app of the same type, webforms .net 2, we do something similar with the following setup:
Using jQuery you can call a method in the page behind of the current page, for example, the following will trigger the AJAX call when the select box called selectBoxName changes, so your code work out the image name here and send it to the server.
$(document).ready(function () {
$('#selectBoxName').change(function (event) {
var image_name = 'calculated image name';
$.ajax({
type: "POST",
url: 'SomePage.aspx/CheckImageName',
data: "{'imageName': '" + image_name + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg);
},
error: function (a, b, c) {
alert("The image could not be loaded.");
}
});
});
});
Where SomePage.aspx is the current page name, and image_name is filled with the name you have already worked out. You could replace the img src in the success and error messages, again using jQuery.
The code behind for that page would then have a method like the following, were you could just reutrn true/fase or the correct image path as a string if needed. You can even return more complex types/objects and it will automatically send back the proper JSON resposne.
[System.Web.Services.WebMethod(true)]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public static bool CheckImageName(string imageName)
{
/*
* Do some logic to check the file
if (file exists)
return true;
return false;
*/
}
As it is .net 2 app, you may need to install the AJAX Extensions:
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&displaylang=en
Could you not use a normal ajax call to the physical path of the image and check if it returns a 404?
Like this:
http://stackoverflow.com/questions/333634/http-head-request-in-javascript-ajax
<script type="text/javascript">
function UrlExists(url) {
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status != 404;
}
function ConstructImage() {
var e = document.getElementById("opt");
var url = '[yourpath]/' + e.value + '.jpg';
if (!UrlExists(url)) {
alert('doesnt exists');
//do stuff if doesnt exist
} else {
alert('exists');
//change img if it does
}
}
</script>
<select id="opt" onchange="ConstructImage()">
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>

Categories

Resources