pass data from JQUERY | AJAX TO HANDLER ASP.NET - c#

I am uploading files to my app and i'am using ajax & jqyery & handel in asp.net
this my code jqyery
$(document).ready(function ()
{
$('#Button1').click(function ()
{
var files = $('#FileUpload1')[0].files;
if (files.length > 0) {
var id = 1;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append(files[i].name, files[i]);
}
$.ajax({
url: 'Handler1.ashx',
method: 'Post',
data: formData,
contentType: false,
processData: false,
success: function () {
alert('success');
},
error: function (err) {
alert(err.error)
}
});
}
});
});
and this my code in handler c#
public void ProcessRequest(HttpContext context)
{
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
string fileName = context.Server.MapPath("~/Uploads/" + System.IO.Path.GetFileName(file.FileName));
file.SaveAs(fileName);
}
}
}
My problem is i need to pass a other variable like id from my jquery to handler someone have any suggestion please

Just do the FormData.Append in your javascript
formData.append('id', 'test1234');
And in your handler access it via Form
var otherData = context.Request.Form;
Happy coding, cheers!

Related

AJAX request within the datatables plugin doesnt work in every part of my code

I am working with ASP.NET MVC 5, jquery and the datatables plugin in a project. My goal is to use the serverside function of datatables in order to retrieve data of a database and then to display the dat in a datatable. This works fine in one part of my code. Here you can see the jquery code where I use the datatables plugin:
var problemTable = $('#ProblemTable').DataTable({
processing: true, // show message while querying fro data
serverSide: true,
ajax: {
url: "/OverView/LoadProblems"
}
});
As you can see in the following picture, the request is successful and my datatables gets filled as it should in the website.
The request URL looks like this:
So far is everything fine. But now comes the part, which is driving me crazy. In a different jquery script I try to call again the the datatables method for a new datatable. The code looks like this:
$('.DeleteEntity').click(
function () {
try
{
var deleteTable = $('#DeleteTable').DataTable({
processing: true,
serverside: true,
destroy: true,
ajax: {
url: "/Administration/ShowEntriesDelete"
}
});
}
catch (e)
{
console.log(e);
}
});
This Ajax call doesnt work anymore. As you can see the following picture, the action method in C# Code fails.
In this case, the request URL looks like this.
So here is my question: Why do I get this behavior although I use the same function in my jquery code? Or is there something which I got totally wrong?
I think that I have tried everything by now, but I still don´t get it. Both datatables look exact the same in HTML, only id and column headers are different.
I also looked for similar questions, but I couldn't find anything. I would be very glad if someone could give me a hint for this.
Best regards!
EDIT:
#Calvin Ananda
I adapted your answer and added both DataTable functions to one script, just for testing purpose. Here is the hole script.
var troubleshootingIDs = [];
$(document).ready(
function () {
// if I call this method, everything works just fine, the c# code throws an error (which it should) but the ajax method is successfull
var problemTable = $('#ProblemTable').DataTable({
processing: true, // show message while querying fro data
serverSide: true,
"ajax": "/Administration/ShowEntriesDelete"
});
// if I call this method, the ajax method doesnt get called, because there is absolute no data provided in the url
var deleteTable = $('#DeleteTable').DataTable({
processing: true,
serverside: true,
destroy: true,
"ajax": "/Administration/ShowEntriesDelete",
"columns": [
{ "data": "Description" },
{ "data": "Connection" },
{ "data": "Action" }
]
});
var table = $('#reasonTable').DataTable({
pageLength: 2,
lengthChange: false,
columnDefs: [
{
targets: [3],
className: "hide_me"
}
]
}
);
var agentButton = $('.agentButton');
$('td').on('click', '#BadgeContainer', function () {
var IDs = [];
$('#DocList').empty();
$('.DocLinkID').each(function (counter) {
IDs[counter] = $(this).html();
});
console.log(IDs);
$.ajax({
url: "/OverView/GetDocuments",
traditional: true,
data: { IDs: IDs },
content: 'application/json; charset=utf-8',
success: listDocuments
});
});
$('#reasonTable tbody').on('click', 'tr', function () {
$('#SolutionList').empty();
troubleshootingIDs = [];
if ($(this).hasClass('selected')) {
}
else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
var selectedReason = $('.ReasonGuid', this).text();
$.ajax({
url: '/OverView/ReasonJson',
contentType: 'application/json; charset=utf-8',
data: { 'selectedReason': selectedReason },
success: handleJsonForWizard
}
);
}
);
$('.SolutionButton').on('click',
function () {
var indexToRemove = [];
var dummyArray = [];
for (var counter = 0; counter < troubleshootingIDs.length; counter++) {
if ($('#q' + (+counter * 2)).hasClass('btn-active')) {
indexToRemove.push(counter);
}
dummyArray[counter] = troubleshootingIDs[counter];
}
for (var counter = indexToRemove.length - 1; counter >= 0; counter--) {
dummyArray.splice(indexToRemove[counter], 1);
}
$.ajax(
{
url: '/OverView/GetSolutions',
contentType: 'application/json; charset=utf-8',
traditional: true,
data: { troubleshootingIDs: dummyArray },
success: function (json) {
$('#SolutionList').empty();
try {
for (var counter = 0; counter < Object.keys(json).length; counter++) {
$('#SolutionList').append('<li class="list-group-item">' + json[counter] + '</li>');
}
}
catch (err) {
}
}
}
);
}
);
$('#ProblemTable tbody').on('click', '.WizardButton',
function () {
var IdToGet = $(this).attr('id');
var url = '/OverView/Wizard?SelectedID=';
window.location.replace(url + IdToGet);
}
);
// Carousel fuction overriding (doesn't work wiht jquery template)
$('.carousel-control.left').click(
function () {
var parentId = '#' + $(this).parent().attr('id');
$(parentId).carousel('prev');
}
);
$('.carousel-control.right').click(
function () {
var parentId = '#' + $(this).parent().attr('id');
$(parentId).carousel('next');
}
);
// comment to define
$('.row #BackToTable').click(
function () {
window.location.replace("/OverView");
}
);
$('body').on('click', '.AgentButton',
function () {
var idNum = $(this).attr('id');
var num = idNum.substring(1);
$('#' + idNum).toggleClass('btn-active');
if ((num % 2) == 0) {
var numToCompare = +num + 1;
var classToCompare = $('#q' + numToCompare).attr('class');
if (classToCompare == 'btn AgentButton btn-active') {
$('#q' + numToCompare).toggleClass('btn-active');
}
}
else {
var numToCompare = +num - 1;
var classToCompare = $('#q' + numToCompare).attr('class');
if (classToCompare == 'btn AgentButton btn-active') {
$('#q' + numToCompare).toggleClass('btn-active');
}
}
}
);
function handleJsonForWizard(json) {
initializeCarousel(json.ImgLinks);
initializeAgent(json.Troubleshootings, json.TroubleshootingIDs);
}
function initializeCarousel(imgLinks) {
$('#ReasonVisualisation > ol').empty();
$('#ReasonVisualisation > .carousel-inner').empty();
for (var counter = 0; counter < Object.keys(imgLinks).length; counter++) {
$('#ReasonVisualisation > ol').append('<li data-target="#ReasonVisualisation" data-slide-to="' + counter + '"></li>');
$('#ReasonVisualisation > .carousel-inner').append('<div class="item"><img src="' + imgLinks[counter] + '"/> </div>');
}
$('#ReasonVisualisation > ol >li:first').addClass('active');
$('#ReasonVisualisation > .carousel-inner>div:first').addClass('active');
var list = $('#ReasonVisualisation > ol').html();
var inner = $('#ReasonVisualisation > .carousel-inner').html();
}
function initializeAgent(troubleshootings, ids) {
$('#Agent').empty();
for (var counter = 0; counter < Object.keys(troubleshootings).length; counter++) {
$('#Agent').append('<div>' + troubleshootings[counter] + ' </div>');
$('#Agent').append('<div class="btn AgentButton" id="q' + (counter * 2) + '">Yes</div>');
$('#Agent').append('<div class="btn AgentButton" id="q' + ((counter * 2) + 1) + '">No</div>');
agentButton = $('.AgentButton');
troubleshootingIDs[counter] = ids[counter];
}
}
function listDocuments(json) {
//Array.isArray(json);
if (json.length > 1) {
for (var counter = 0; counter < json.length; counter++) {
$('#DocList').append('<li> <a href=\"' + json[counter] + '\" > Link </a></li>');
}
}
}
}
);
The most interesting part are the first to methods within the script. In my provided code within the code I described my issue. I simply don´t why ajax reacts so different...
I use this method in my project, and it works.
But I dont know if it works to answer your problem.
JSFiddle Here
Change to "ajax": "/OverView/LoadProblems"
var problemTable = $("#ProblemTable").DataTable({
processing: true, // show message while querying fro data
serverSide: true,
"ajax": "/OverView/LoadProblems"
});
=========================================================================
$(".DeleteEntity").click(
function () {
try
{
var deleteTable = $("#DeleteTable").DataTable({
processing: true,
serverside: true,
destroy: true,
"ajax": "/Administration/ShowEntriesDelete"
});
}
catch (e)
{
console.log(e);
}
});

Button Click is not working after WebMethod function

On my web page I used jquery and ajax to call a C# function to fill Dropdown list with respect to another
Dropdown Branch is filled as per the selection of zone and Employee with the selection of branch.It works perfect But the button Click is not working after this.Someone please tell me why this button click is not working??
[Button click works when no drop down selection is made]
my Code look Like this:
Jquery
<script src="jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(function () {
$('#<%= ddZone.ClientID %>').change(function () {
$.ajax({
type: "POST",
url: "Reports.aspx/BranchFill",
data: "{'Zone':'" + $("[id*=ddZone] option:selected").text() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
function OnSuccess(response) {
var ddlBranch = $("[id*=ddBranch]");
ddlBranch.empty().append('<option selected="selected" value="0">--Select--</option>');
$.each(response.d, function () {
ddlBranch.append($("<option></option>").val(this['Value']).html(this['Text']));
});
if (response.d == "false") {
alert("Not found");
}
}
});
$('#<%= ddBranch.ClientID %>').change(function () {
$.ajax({
type: "POST",
url: "Reports.aspx/EmployeeFill",
data: "{'Branch':'" + $(this).val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
function OnSuccess(response) {
var ddlEmployee = $("[id*=ddEmployee]");
ddlEmployee.empty().append('<option selected="selected" value="0">--Select--</option>');
$.each(response.d, function () {
ddlEmployee.append($("<option></option>").val(this['Value']).html(this['Text']));
});
if (response.d == "false") {
alert("Not found");
}
}
});
});
</script>
C#
[System.Web.Services.WebMethod(EnableSession = true)]
public static Object BranchFill(string Zone)
{
string result = string.Empty;
var obj = new Reports();
List<ListItem> Branch = new List<ListItem>();
DataTable dt = obj.CS.StaticZoneBranch(Zone, "", "SelectBranch");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Branch.Add(new ListItem
{
Text = dt.Rows[i]["Name"].ToString(),
Value = dt.Rows[i]["Code"].ToString()
});
}
return Branch;
}
else
{
return "false";
}
}
[System.Web.Services.WebMethod(EnableSession = true)]
public static Object EmployeeFill(string Branch)
{
string result = string.Empty;
var obj = new Reports();
List<ListItem> Employee = new List<ListItem>();
DataTable dt = obj.CS.StaticZoneBranch("", Branch, "SelectEmployee");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Employee.Add(new ListItem
{
Text = dt.Rows[i]["Name"].ToString(),
Value = dt.Rows[i]["Employee Id"].ToString()
});
}
return Employee;
}
else
{
return "false";
}
}
And the button Click(which is not working)
protected void Button1_Click(object sender, EventArgs e)
{
ReportClass RC = new ReportClass();
if (ddZone.SelectedValue !="0")
{
RC.Zone = ddZone.SelectedValue;
RC.Branch = ddBranch.SelectedValue;
RC.EmployeeId = ddEmployee.SelectedValue;
Report = RC.GetReport();
}
}
Why this click function is not Working, please help me to know..

First Row activate Works only in activate all button jQuery c#

This is my c# code for Activate all button:
[WebMethod]
public static void ActivateSelected(String Id)
{
clsCategoryBL objproject = new clsCategoryBL();
string[] arr = Id.Split(',');
string strid = arr[2];
foreach (var id in arr)
{
if (!string.IsNullOrEmpty(id))
{
objproject.CategoryStatus(Convert.ToInt32(strid), true);
}
}
BindDatatable();
}
This is my jquery table bind code:
function ActivateSelected() {
var ids = '';
var cells = Array.prototype.slice.call(document.getElementById("example1").getElementsByTagName('td'));
debugger;
for (var i in cells) {
var inputArray = cells[i].getElementsByTagName('input');
for (var i = 0; i < inputArray.length; i++) {
if (inputArray[i].type == 'checkbox' && inputArray[i].checked == true) {
debugger;
ids += inputArray[i].id + ',';
}
}
}
debugger;
var urldata = "Category.aspx/ActivateSelected";
$.ajax(
{
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "true",
cache: "false",
url: urldata,
data: "{Id:'" + ids + "'}",
success: function (dt) {
debugger;
location.reload();
$("#example1").DataTable();
//$("#example1").bind;
debugger;
},
error: function (result) {
alert("Error");
//console.log();
//alert(result);
}
});
}
The problem is that when select all the checkbox and click on Activate all button only First row status is activate instead of All row status,So kindly help me out.
This is my activate all button:
<i class="fa fa-check-square-o" name="activatebtn" onclick='ActivateSelected();' style='font-size:22px;margin-left: 32px;color:green'>Activate Selected</i>
This is the code for select all the checkbox:
function Selectallcheckbox() {
var cells = Array.prototype.slice.call(document.getElementById("example1").getElementsByTagName('td'));
var check = document.getElementById('chkall');
if (check.checked) {
for (var i in cells) {
var inputArray = cells[i].getElementsByClassName('chk');
for (var i = 0; i < inputArray.length; i++) {
inputArray[i].checked = true;
}
}
}
else {
for (var i in cells) {
var inputArray = cells[i].getElementsByClassName('chk');
for (var i = 0; i < inputArray.length; i++) {
inputArray[i].checked = false;
}
}
}
}
I think the problem is here(c#):
string strid = arr[2];
In strid only one id is comes..and only one id is binding in
objproject.CategoryStatus(Convert.ToInt32(strid), true);
If i am using Id instead of strid on above line it provides me error due to last comma..input string was not in correct format..
Edit this line to objproject.CategoryStatus(Convert.ToInt32(id), true); I have changed strid to id the foreach loop variable.

Sending object to a controller in asp.net mvc using ajax

I have issue with sending object contains array to a controller
this is my js code
var messageId = 0;
function DraftMessage()
{
var to = [];
var i = 0;
$('#to option:selected').each(function (index, element) {
to[i++] = $(element).val();
});
console.log(to);
$.ajax({
type: "POST",
url: "#Url.Action("DraftMessage", "Activities")",
datatype: "json",
traditional: true,
async: false,
data: { "id": messageId, "To": to, "Title": $("#title").val(), "Project": $("#project").val(), "AreaId": $("#areaId").val(), "Body": $("#messageBody").val() },
beforeSend: function () { }
}).done(function (Id) {
console.log(Id);
messageId = Id;
});
}
$("input, select, textarea").change(function () { DraftMessage(); });
var contents = $('.note-editable').html();
$(".compose-message").on("blur", ".note-editable", function () {
if (contents != $(this).html()) {
DraftMessage();
contents = $(this).html();
}
});
and this is my controller side
public int DraftMessage(message draftMessage, HttpPostedFileBase[] files = null)
{
return new MessageActions().DraftMessage(draftMessage);
}
my issue is that the ajax request always send the to array as null, I do not know what is wrong so could anyone help me to resolve this issue.
Can you change your request and use
dataType: "json",
contentType: "application/json;charset=utf-8",
This should work. Please let me know.
Try this. Push your object to array and send it as Json.
array.push({yourobject datas here})
$.ajax({
type: "POST",
url: '/DraftMessage/Activities',
contentType: 'application/json',
data: JSON.stringify(array),
success: function (d) {
..
},
error: function (xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
Convert your controller function's return type to JSonResult.
Hope helps.
do you want upload file using ajax ?!!
use the normal usage of form not the Ajax.BeginForm then in form submit event
write your code like this:
$('#Form').submit(function () {
var xhr = new XMLHttpRequest();
var fd = new FormData();
var file = $('#Image').val();
if (file) {
var fname = $('#Image')[0].files[0].name;
if (CheckFile(file)) {
var uploadFile = document.getElementById('Image').files[0];
var myArray = [];
myArray.push(uploadFile);
if (myArray.length > 0) {
for (var i = 0; i < myArray.length; i = i + 1) {
fd.append("File1", myArray[i]);
}
}
}
else {
return false;
}
}
fd.append("ID", messageId);
fd.append("Title", $('#Title').val());
fd.append("Project", $('#Project').val());
fd.append("AreaId", $('#AreaId').val());
fd.append("Body", $('#messageBody').val());
var form = $('#Form');
var token = $('input[name="__RequestVerificationToken"]', form).val();
fd.append("__RequestVerificationToken", token);
xhr.open("POST", "/ControllerName/Action/", true);
xhr.send(fd);
xhr.addEventListener("load", function (event) {
if (event.target.response != "OK") {
OnFail(event.target.response);
}
else {
OnSuccess(event);
}
}, false);
return false;
})
server side in controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult actionName(Model pModel){
HttpPostedFileBase File = Request.Files["File1"];
if (File != null && File.ContentLength != 0){
//do what you want
return Content("OK");
}
else{
Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
return Content("Error Messages", System.Net.Mime.MediaTypeNames.Text.Plain);
}
}
You can try a different approach. You can serialize your entire form by doing something like this:
var formdata = $("#frmEmailInfo").serialize();
and then post it to the Controller:
$.ajax(
{
type: "POST",
data: formdata,
dataType: 'json',...

New Excel file with OfficeOpenXml in ASP.Net MVC : nothing is returned

Context
I create an Excel file with OfficeOpenXml, but nothing is returned to browser.
Any idea why ?
Code
[C#] :
public ActionResult ExportToExcel(string[] mails)
{
using (var ep = new ExcelPackage())
{
var ws = ep.Workbook.Worksheets.Add("Contacts");
for (var i = 0; i < mails.Length; i++)
{
ws.Cells[i + 1, 1].Value = mails[i];
}
Byte[] bytes = ep.GetAsByteArray();
return new FileContentResult(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { FileDownloadName = "Contacts.xls" };
}
}
[JavaScript] :
$('#contacts-excel-btn').click(function () {
var mails = [],
uniqueMails = [];
$('.email-td').each(function () {
var txt = $(this).text();
if (txt) {
mails.push(txt);
}
});
$.each(mails, function (i, el) {
if ($.inArray(el, uniqueMails) === -1) {
uniqueMails.push(el);
}
});
if (uniqueMails[0]) {
$.ajax({
type: 'POST',
url: '/Contact/ExportToExcel',
dataType: 'json',
traditional: true,
data: { mails: uniqueMails }
});
}
});
Ok I solved my issue.
According to this article, I replaced my return with:
var butes = ep.GetAsByteArray();
var fileName = "Contacts.xlsx";
return base.File(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
And according to this article, I replaced my ajax approach by a html form approach:
[JS] :
$.each(uniqueMails, function (i, el) {
$('#contacts-excel-form').append('<input type="hidden" name="mails[' + i + ']" value="' + el + '" />');
});
$('#contacts-excel-form').submit();
[C#] :
var mails = Request.Form.AllKeys;
for (var i = 0; i < mails.Length; i++)
{
ws.Cells[i + 1, 1].Value = Request.Form[mails[i]];
}

Categories