Passing HttpPostedFileBase and other variables in ajax POST to mvc controller - ajax

I have been trying to post a file and some variables to my controller action using ajax, but I am getting null parameters for both of my variables.
Below is my ajax call
$("#btn-upload").on("click", function () {
var rows =$("[name='rows']").val();
var formData = new FormData($('#excel-upload-form')[0]);
var Data = formData+"&rows="+rows;
$.ajax({
url: '/MVC/UploadExcel/UploadExcel',
type: 'POST',
data: Data,
cache: false,
contentType: false,
processData: false,
success: function (result) {
if (result=='True') {
$(".alert-success").show();
}
else {
$(".alert-danger").show();
}
},
error: function (jqXHR, textStatus, errorThrown) {
$(".alert-danger").show();
},
});
});
and my controller action is
[HttpPost]
public bool UploadExcel(HttpPostedFileBase uploadedFile, int? rows)
{
var excelUtility = new ExcelUtilityService();
bool success=false;
if ((uploadedFile != null || uploadedFile.ContentLength > 0)&& rows !=null)
{
success = excelUtility.ProcessFile(uploadedFile, rows);
}
return success;
}
If I pass only the file parameter in my ajax call it works fine but when I try to do it with multiple parameters e.g 'rows' in my code, both of the parameters become null in my controller action while post.

In order to add values to a FormData object, you need to use .append().
Modify your script to
$("#btn-upload").on("click", function ()
var rows =$("[name='rows']").val();
var formData = new FormData($('#excel-upload-form')[0]);
formData.append('rows', rows); // modify
$.ajax({
url: '/MVC/UploadExcel/UploadExcel',
type: 'POST',
data: formData, // modify
cache: false,
contentType: false,
processData: false,
success: function (result) {
....

Using the script modification from Stephen:
$("#btn-upload").on("click", function ()
var rows =$("[name='rows']").val();
var formData = new FormData($('#excel-upload-form')[0]);
formData.append('rows', rows); // modify
$.ajax({
url: '/MVC/UploadExcel/UploadExcel',
type: 'POST',
data: formData, // modify
cache: false,
contentType: false,
processData: false,
success: function (result) {
....
If linking to parameters directly doesn't work with the formData.append() method above, I would recommend accessing them via:
Request["key-used-to-append"]
Example with your controller (rows variable assignment):
[HttpPost]
public bool UploadExcel(HttpPostedFileBase uploadedFile)
{
var excelUtility = new ExcelUtilityService();
var rows = Request["rows"];
bool success=false;
if ((uploadedFile != null || uploadedFile.ContentLength > 0)&& rows !=null)
{
success = excelUtility.ProcessFile(uploadedFile, rows);
}
return success;
}

Related

Passing more then 1 value to webmethod using FormData via Ajax

I'm trying to pass the uploaded image + two additional parameters to my web service using the FormData method from my Ajax method as shown here:
var formData = new FormData();
formData.append('file', $('#photo')[0].files[0]);
formData.append('u', "test");
formData.append('s', "Testing");
My ajax call is outlined like so:
$.ajax({
url: "/admin/WebService/test.asmx/UploadImage",
type: "POST",
processData: false,
contentType: false,
data: formData,
success: function (response) {
console.log(response);
},
error: function (er) {
alert(er);
}
});
Which calls this webmethod:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string UploadImage()
{
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var t= System.Web.HttpContext.Current.Request.Files["s"];
var c= System.Web.HttpContext.Current.Request.Files["u"];
var p = System.Web.HttpContext.Current.Request.Files["file"];
}
else
{
return "Error";
}
return "Error";
}
The issue I'm having is the parameters 'u' and 's' are null yet when referencing file I'm able to get its value.
Whilst searching the web I was under the impression you can specify as many key/values are required when using this approach unless I have been misinformed? can someone please shed some light into why these two parameters are null? Thanks in advance.
This works for me:
JavaScript
var formData = new FormData();
formData.append("UserId", userId);
formData.append("RequestPhoto", imageFile);
formData.append("RequestVoiceRecord", voiceFile);
formData.append("Latitude", latitude);
formData.append("Longitude", longtitude);
$.ajax({
type: "POST",
url: "/User/CreateRequest",
data: formData,
contentType: false,
processData: false,
success: function () {
alert("OK");
},
error: function () {
alert("Error");
}
});
Controller:
public class UserController : ApiController
{
[HttpPost]
public int CreateRequest()
{
// HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
var req = new UserRequest
{
UserId = Guid.Parse(httpRequest.Form["UserId"]),
Photo = httpRequest.Files["RequestPhoto"],
VoiceRecord = httpRequest.Files["RequestVoiceRecord"]
Latitude = float.Parse(httpRequest.Form["Latitude"]),
Longitude = float.Parse(httpRequest.Form["Longitude"]),
};
You should create one json instead of create this stuff, add whatever keys you want to sent via ajax.
var formData = {'u':'value','s':'value'}
$.ajax({
url: "/admin/WebService/test.asmx/UploadImage",
type: "POST",
processData: false,
contentType: false,
data: JDON.Stringify(formData),
success: function (response) {
console.log(response);
},
error: function (er) {
alert(er);
}
});
try using this way.

Ajax Form Submit with attachment

I have a Form on my Site thats submitted true ajax. This Form has a field where to attache .pdf files. How when submitting the form though the file is not send with the rest of data.
How can i get this to work?
Here is my ajax code:
$('#submit_btn').click(function () {
$.ajax({
type: 'POST',
url: '/contact.php',
dataType: "json",
data: $('#contactform').serialize(),
success: function (data) {
console.log(data.type);
console.log(data.msg);
var nClass = data.type;
var nTxt = data.msg;
$("#notice").attr('class', 'alert alert-' + nClass).text(nTxt).remove('hidden');
//reset fields if success
if (nClass != 'danger') {
$('#contactform input').val('');
$('#contactform textarea').val('');
}
}
});
return false;
});
On the php side i have phpmailer setup and am handling the file so:
if(!empty($_FILES['file'])) {
$_m->addAttachment($_FILES['file']['tmp_name'],$_FILES['file']['name']);
}
$('#submit_btn').click(function () {
var formData = new FormData($('#contactform'));
$.ajax({
type: 'POST',
url: '/contact.php',
// dataType: "json",
data: formData ,
processData: false,
contentType: false,
success: function (data) {
console.log(data.type);
console.log(data.msg);
var nClass = data.type;
var nTxt = data.msg;
$("#notice").attr('class', 'alert alert-' + nClass).text(nTxt).remove('hidden');
//reset fields if success
if (nClass != 'danger') {
$('#contactform input').val('');
$('#contactform textarea').val('');
}
}
});
return false;
});

Binding json response to label

public JsonResult GetPrice(List<int> modelValues)
{
List<int> model = new List<int>();
try
{foreach(var d in modelValues)
model.Add(d);
}
return Json(model, JsonRequestBehavior.AllowGet);
}
function GetDetail() {
var jsonUrl = Home/GetPrice";
$.ajax({
cache: false,
url: jsonUrl,
type: "POST",
data: "{}",
contentType: "application/json",
dataType: 'json',
async: true,
success: function (data) {
},
error: function (x, t, m) {
}
});
I want my values present in model to display in label.It should be done by binding data using ajax call. Can someone please suggest me a solution? Label id="name" in html file.

retrieve the result of an ajax request as a variable

How can I get the result of my ajax post into a variable:
function decode_original(hshdecode) {
var decode_original = 'decode=1&hashvalue=kjh4k5hq35l&hashkey=12345';
$.ajax({
type: "POST",
async: false,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
url: 'decode_function.php',
data: decode_original,
cache: false,
success: function(return_value) {
var decoded_value = return_value;
console.log("Decoded Value:" +decoded_value);
return decoded_value;
},
error: function(data){
return data;
}
});
}
The above actually gets the return value successfully, but I am unable to pass the result into a variable:
var decode_value = decode_original(encoded_value);
alert(decode_value);
use responseText like :
success: function(return_value) {
var decoded_value = return_value.responseText;
console.log("Decoded Value:" +decoded_value);
return decoded_value;
}

Send JSON string to a C# method

In my ASP.NET page I have the following method:
public static void UpdatePage(string accessCode, string newURL)
{
HttpContext.Current.Cache[accessCode] = newURL;
}
It actually should receive the accessCode and newURL and update the Cache accordingly. I want to pass the values to that method from JavaScript, using an AJAX request. The code for it is as follows:
function sendUpdate() {
var code = jsGetQueryString("code");
var url = $("#url_field").val();
var dataToSend = [ {accessCode: code, newURL: url} ];
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "lite_host.aspx/UpdatePage",
data: {"items":dataToSend},
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response) { var results = response.d; } };
$.ajax(options);
}
However this doesn't seem to work. Could anybody help me figure out where the bug is?
UpdatePage is a void method that doesn't return anything, so there is nothing to look at in the response.
You could look at the HTTP return code and check that it was 200 OK or you could modify the web method:
public static bool UpdatePage(string accessCode, string newURL)
{
bool result = true;
try {
HttpContext.Current.Cache[accessCode] = newURL;
}
catch {
result = false;
}
return result
}
Edit:
It looks like your JSON arguments to the WebMethod are incorrect, you don't need the "items" in your JSON. The arguments should match your webmethod exactly.
function sendUpdate() {
var code = jsGetQueryString("code");
var url = $("#url_field").val();
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "lite_host.aspx/UpdatePage",
data: {'accessCode': code, 'newURL': url},
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response) { var results = response.d; } };
$.ajax(options);
}

Resources