FileUpload formData in ASP.NET WebForms - c#

I have some problem with posting formData to server side action method. Because ajax call doesn't send files to server, I have to add file uploader data to formData manually like this
It is impossible to call a server method
[WebMethod]
public HttpPostedFileBase Name(HttpPostedFileBase file)
{
string ret = "test";
return file;
}
Errors on the client side no
I wrote jQuery function that need to post form data to server using ajax call.
this is my script:
data.append(self.idFileInput, file[f]);
$.ajax({
type: "POST",
url: "/AddContract.aspx/Name",
data: data,
dataType: 'json',
contentType: false,
processData: false,
success: function (data) {
}
});
Any tips, link or code example would be useful.
Thank you in advance!

try to use contentType: 'application/json; charset=utf-8',
$.ajax({
type: "POST",
url: "AddContract.aspx/Name",
data: { field1: self.idFileInput, field2 : file[f]} ,
dataType: 'json',//Remove this line this line is causing issue.
contentType: 'application/json; charset=utf-8',
processData: false,
success: function (data) {
}
});

In a previous answer I said something stupid about ASPX not supporting WebMethod calls, which they do.
Now a real answer:
In order to post a file you need to use the ajaxSubmit method. See this reference.

Related

jquery $.when not working by waiting function in master page

i have some problem when i use jquery.when function in web form using master page
This is my code in web form using master page
$(document).ready(function(){
$.when(masterPageFunction()).done(function(){
webFormFunction();
});
})
And this my master page
function masterPageFunction() {
//In this function i call 2 ajax like this
$.ajax({
type: "POST",
url: "/api/master/xxx/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.ajax({
type: "POST",
url: "/api/master/xxx2/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
}
})
}
})
}
result is web function is running when master page function not done
please help, thank you so much
You're close, but the when, then and done functions rely on promises. You aren't returning any promises in your code, so it's just running straight through.
First, you'll need to obtain the result of the promise after it completes in the done function in your master page. We'll do that by adding a response parameter to the callback, then passing it through to webFormFunction.
$(document).ready(function(){
$.when(masterPageFunction()).done(function(response){
webFormFunction(response);
});
})
Next, we need to add a promise to masterPageFunction and return it. You resolve the promise with the response you want to send back to the done function in your master page. Like so:
function masterPageFunction() {
// Create the promise
var deferred = $.Deferred();
//In this function i call 2 ajax like this
$.ajax({
type: "POST",
url: "/api/master/xxx/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.ajax({
type: "POST",
url: "/api/master/xxx2/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// Resolve the promise with the response from $.ajax
deferred.resolve(response);
}
});
}
});
// Return the promise (It hasn't been resolved yet!)
return deferred.promise();
}
In this way, webFormFunction won't be called until the second ajax call completes, which resolves the promise.

How to pass image using jquery asp.net

Hi I am new to ASP and wondering how to pass an image from the input file using jquery ajax.
I am supposed to pass the path and get the image in the server side? is it possible?
or are there any alternative on it?
what I am doing is that I want to upload a photo while checking if the user is currently in session.
I used ajax so I dont refresh my page everytime I hit the upload button.
$.ajax({
type: "POST",
url: 'Upload.aspx/uploadPhoto',
data: "{ ???? }", <-- what Should I put it here??
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
}
});
Is it the right way to upload a photo while checking the session in the webmethod?
var formData = new FormData();
formData.append('file', $('#youruploadbuttonid')[0].files[0]);
$.ajax({
type: "POST",
url: 'Upload.aspx/uploadPhoto',
data: formData,
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
}
});
var formData = new FormData();
formData.append('file', $('#youruploadbuttonid')[0].files[0]);
$.ajax({
type: "POST",
url: 'Upload.aspx/uploadPhoto',
data: formData,
processData: false,
contentType: false,
success: function (data) {
alert(data);
}
});

Send just a string from $.ajax to c#

This is supposedly very easy but for some reason it has taken me about 2 hours and countless searches and nothing is working
I am trying to call a WebMethod from ajax, and it works quite well.
As soon as I try to change the c# function to accept parameters and send one from ajax everything fails
Code:
c#:
[WebMethod]
public static string GetBGsForSelectedCrop(string cropName)
{
return "asdasd";
}
jquery:
$().ready(function () {
$("#Result").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetBGsForSelectedCrop",
data: "Wheat",
success: function (msg) {
$("#Result").text(msg.d);
alert(msg.d);
console.log(msg)
}
});
});
});
I have tried datatype: "json", contentType: "application/json; charset=utf-8", and tried without both and datatype: "string" and datatype: "text", GET, data: "{'ABCD'}, data:{"cropName: Wheat"}, and data: json.Stringify("Wheat").
I get undefined for msg.d and sometimes HTTP error 500 if I take it too far.
What am I missing? It is just a simple task and should've been done in seconds..
As the guys in the comments says, you need to change your code for:
$("#Result").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetBGsForSelectedCrop",
data: JSON.stringify({ cropName: "Wheat" }),
dataType:'text',
contentType: "application/json; charset=utf-8",
success: function (msg) {
$("#Result").text(msg.d);
alert(msg.d);
console.log(msg)
}
});
});
Your error is the data is no good encoded, and you are missing the datatype.
What is the stringfy It Convert any value to JSON.

Data Format Jquery Ajax Post Cross Domain Call Asp.Net MVC method

I am trying $.ajax post MVC call from http to https cross domain.
Client Side
enter code here
$.ajax({
type: 'post',
crossDomain: true,
url: 'https://localhost/views/Member/VerifyEmail',
beforeSend: function () { alert('I am sending'); },
data: '{name:"John"}',
dataType: "json",
success: function (data) { pdata = data; }
});
Server Side
[RequireHttps]
[HttpPost]
public string VerifyEmail(string name){
return "got it"
}
I have added Access-Control-Allow-Origin to web.config so the call can be established fine. Now the problem is on server side I got variable name = null
I have also checked debugging and found the data has actually been send to server
HttpContext.Request.Form
{%7bname%3a%22hello%22%7d}
[System.Web.HttpValueCollection]: {%7bname%3a%22hello%22%7d}
The question is how I could retrieve it from the web method?
%7bname%3a%22hello%22%7d This is HTML entity String please Decode the String then parse for JSON.
I think you can change your call to
$.ajax({
type: 'post',
crossDomain: true,
url: 'https://localhost/views/Member/VerifyEmail',
beforeSend: function () { alert('I am sending'); },
data: 'John',
dataType: "text",
success: function (data) { pdata = data; }
});

Javascript - jquery ajax post error driving me mad

Can't seem to figure this one out.
I have a web service defined as (c#,.net)
[WebMethod]
public string SubmitOrder(string sessionid, string lang,int invoiceno,string email,string emailcc)
{
//do stuff.
return stuff;
}
Which works fine, when I test it from the autogenerated test thingy in Vstudio.
But when I call it from jquery as
$j.ajax({
type: "POST",
url: "/wservice/baby.asmx/SubmitOrder",
data: "{'sessionid' : '"+sessionid+"',"+
"'lang': '"+usersettings.Currlang+"',"+
"'invoiceno': '"+invoicenr+"',"+
"'email':'"+$j(orderids.txtOIEMAIL).val()+"',"+
"'emailcc':'"+$j(orderids.txtOICC).val()+"'}",
contenttype: "application/json; charset=utf-8",
datatype: "json",
success: function (msg) {
submitordercallback(msg);
},
error: AjaxFailed
});
I get this fun error:
responseText: System.InvalidOperationException: Missing parameter: sessionid. at
System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection) at
System.Web.Services.Protocols.HtmlFormParameterReader.Read(HttpRequest request) at
System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() at
System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
data evaluates to: {'sessionid' : 'f61f8da737c046fea5633e7ec1f706dd','lang': 'SE','invoiceno': '11867','email':'steve#jobs.com','emailcc':''}
Ok, fair enough, but this function from jquery communicates fine with another webservice.
Defined:
c#:
[WebMethod]
public string CheckoutClicked(string sessionid,string lang)
{
//*snip*
//jquery:
var divCheckoutClicked = function()
{
$j.ajax({
type: "POST",
url: "/wservice/baby.asmx/CheckoutClicked",
data: "{'sessionid': '"+sessionid+"','lang': '"+usersettings.Currlang+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
divCheckoutClickedCallback(msg);
},
error: AjaxFailed
});
}
data: {sessionid: sessionid,
lang: usersettings.Currlang,
invoiceno: invoicenr,
email: $j(orderids.txtOIEMAIL).val(),
emailcc: $j(orderids.txtOICC).val()
},
Refer to http://encosia.com/2010/05/31/asmx-scriptservice-mistake-invalid-json-primitive/
Short version is,
Be sure to set data as a string using this format
// RIGHT
$.ajax({
type: 'POST',
contentType: 'application/json',
dataType: 'json',
url: 'WebService.asmx/Hello',
data: '{ FirstName: "Dave", LastName: "Ward" }'
});
it has to be double quotes inside the string.
You can simplify the JSON creation and make it less brittle by using JSON.stringify to convert a client-side object to JSON string. JSON.stringify is built into newer browsers as a native feature, and can be added to older browsers by including Douglas Crockford's json2.js.
Take a look at this post on using JSON and data transfer objects with ASMX ScriptServices for some examples. Its examples start in almost exactly the same predicament that you're currently in, so hopefully it will be helpful.
remove the single quotes;
data: "{sessionid : "+sessionid+","+
"lang: "+usersettings.Currlang+","+
"invoiceno: "+invoicenr+","+
"email:"+$j(orderids.txtOIEMAIL).val()+","+
"emailcc:"+$j(orderids.txtOICC).val()+"}",
contenttype: "application/json; charset=utf-8",
and move the curly brace outside the quotes
data should be more like data: {sessionid : sessionid, lang: usersettin...
the way you're sending it now, it's a string.. so your application is NOT getting the variable sessionID and it's value.
Thus, it's reporting an error. this error is not json, so responseText is throwing an error.

Categories

Resources