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.
Related
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!
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..
I have a table full of checkboxes, and at the top there's a select all checkbox. Once clicked, I am making an ajax call that passes in a list of invoice_ids as well as the check_run_id of another table. What I'm having difficulty with is setting the property of an object based on the index of the list of invoices. The code will probably explain better. Thanks for any help.
public static void SaveInvoicesForPayment(List<int> invoiceIDs, int checkRunID)
{
using (MiniProfiler.Current.Step("SaveInvoices()"))
using (var context = rempscoDataContext.CreateContext())
{
toSave = invoiceIDs.Where(i => i > 0);
var toDelete = invoiceIDs.Where(i => i < 0).Select(i => -i);
toSave = toSave.Where(i => !toDelete.Contains(i));
var db_invoice_to_update = context.vendor_invoices.Where(si => toDelete.Contains(si.invoice_id));
var db_check_run_details_to_delete = context.check_run_details.Where(crd => crd.check_run_id == checkRunID);
db_invoice_to_update.ToList().ForEach(vi => { vi.check_run_id = null; });
db_check_run_details_to_delete.ToList().ForEach(crd => {
crd.bank_draft_id = null;
crd.is_active = false;
});
var invoice_to_save = context.vendor_invoices.Where(si => toSave.Contains(si.invoice_id)).ToList();
foreach (var crd in invoice_to_save)
{
context.check_run_details.InsertOnSubmit(new check_run_detail
{
invoice_id = crd.invoice_id,
check_run_id = checkRunID,
add_user = Security.CurrentUser,
add_date = DateTime.Now,
edit_user = Security.CurrentUser,
edit_date = DateTime.Now,
invoice_amount = **invoice_to_save[index??],**
is_active = true,
});
}
context.SubmitChanges();
}
}
Here's the ajax call as well just in case:
function doSaveInvoices($parent, checked) {
var $invoiceCheckBoxes = $parent.find('input.invoice[type="checkbox"]');
var checkRunID = $("#checkRunID").val();
var invoiceIDs = [];
if (checked) {
$invoiceCheckBoxes.each(function (i, c) {
var $checkbox = $(this);
invoiceIDs.push($checkbox.attr('invoice_id'));
$checkbox.attr('checked', true);
});
}
else {
$invoiceCheckBoxes.each(function (i, c) {
var $checkbox = $(this);
invoiceIDs.push(-$checkbox.attr('invoice_id'));
$checkbox.attr('checked', false);
});
}
var js = JSON.stringify({ invoiceIDs: invoiceIDs, checkRunID: checkRunID });
$.ajax({
url: './PayInvoicesWS.asmx/SaveInvoices',
data: js,
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
success: function (data) {
calculateTotal();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
sendErrorEmail(window.location.href, 'SaveInvoices', XMLHttpRequest);;
}
});
I have two ASP ListBoxes. As you can see below, lbAvailable is populated on PageLoad with WebMethod and populates all cities. LbChoosen is populated depending on DropDown Value Chosen. The Dropdown has 4 options(ALL, Top25, Top50, Top100). for example if you choose Top 25 which is value 4, lbChosen populates top 25 cities (This all works).
MY PROBLEM IS lbAvaliable always populates all cities. So if i chose top 25 which populates top25 cities into lbChoosen, how can those value (top25 cities) be removed from lbAvailable
function LoadMarketsAvailableJS() {
var ddlFootprint = $('#ddlFootprint');
var lbChoosen = $('#lbChoosen');
var lbAvailable = $('#lbAvailable');
lbChoosen.empty();
var SelectedMarkets = [];
var url = "";
//Load lbAvailable on Page Load with all Markets
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Campaign.aspx/LoadAvailableMarkets",
dataType: "json",
success: function (msg) {
var obj = $.parseJSON(msg.d);
for (var i = 0; i < obj.Markets.length; i++) {
if (SelectedMarkets.indexOf(obj.Markets[i].id.toString()) == -1) {
$("#lbAvailable").append($("<option></option>")
.attr("value", obj.Markets[i].id)
.text(obj.Markets[i].name + " - " + obj.Markets[i].rank));
}
}
},
error: function(result) {
alert("Error");
}
});
//Check DropdownList
if (parseInt(ddlFootprint.val()) == 1) {
url = 'Campaign.aspx/LoadAvailableMarkets';
} else if (parseInt(ddlFootprint.val()) == 2) {
url = 'Campaign.aspx/LoadTop100Markets';
}
else if (parseInt(ddlFootprint.val()) == 3) {
url = 'Campaign.aspx/LoadTop50Markets';
}
else if (parseInt(ddlFootprint.val()) == 4) {
url = 'Campaign.aspx/LoadTop25Markets';
}
else if (parseInt(ddlFootprint.val()) == 5) {
url = 'Campaign.aspx/LoadAvailableMarkets';
}
//Load Select Dropdown Value to lbChoosen
if (url.length > 0) {
$.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var obj = $.parseJSON(msg.d);
for (var i = 0; i < obj.Markets.length; i++) {
if (SelectedMarkets.indexOf(obj.Markets[i].id.toString()) == -1) {
lbChoosen
.append($("<option></option>")
.attr("value", obj.Markets[i].id)
.text(obj.Markets[i].name + " - " + obj.Markets[i].rank));
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
},
complete: function (jqXHR, textStatus) {
}
});
}
}
Assuming I've understood what you're asking, if you want to remove options from lbAvailable as they're added to lbChoosen you should be add the following line:
lbAvailable.find('option[value="' + obj.Markets[i].id + '"]').remove();
So your code will look something like:
success: function (msg) {
var obj = $.parseJSON(msg.d);
for (var i = 0; i < obj.Markets.length; i++) {
if (SelectedMarkets.indexOf(obj.Markets[i].id.toString()) == -1) {
lbChoosen
.append($("<option></option>")
.attr("value", obj.Markets[i].id)
.text(obj.Markets[i].name + " - " + obj.Markets[i].rank));
lbAvailable.find('option[value="' + obj.Markets[i].id + '"]').remove();
}
}
},
i have an ajax AutoCompleteExtender. I am able to bind the text only with my AutoCompleteExtender not image. So How can i bind the image and text in an ajax AutoCompleteExtender? Any help is greatly appreciated.
Add below mentioned files in your header section
<script type="text/javascript">
$(document).ready(function () {
$("#searchtext").autocomplete
({
source:
function (request, response) {
$.ajax
({
url: "../BeanService.asmx/GetCompletionList",
data: "{prefixText:'" + request.term + "'}", // term is the property that contains the entered text
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response(data["d"]); // property d contains list of names sent from service
//$("#dynamiccontainer").append(data["d"]);
},
error: function (xhr, callStatus, errorThrown) {
// alert(callStatus);
}
});
},
// Attempt to remove click/select functionality - may be a better way to do this
select: function (event, ui) {
var mylink = ui.item.value;
var doc = document.createElement("html");
doc.innerHTML = mylink;
var links = doc.getElementsByTagName("a")
var urls = [];
for (var i = 0; i < links.length; i++) {
urls.push(links[i].getAttribute("href"));
}
window.location.href = urls[0];
return false;
}
});
});
</script>
Below is the Textbox on which autocomplete will be applied
<asp:TextBox ID="searchtext" runat="server"></asp:TextBox>
This is your bean class which will be filled by webservice and returned to jquery method through ajax call
public class SearchBean
{
public int Id
{
get;
set;
}
public string Title
{
get;
set;
}
public string reUrl
{
get;
set;
}
public string stype
{
get;
set;
}
public string photoAdd
{
get;
set;
}
}
This is your webservice which will be called by your jquery automplete ajax method
public string[] GetCompletionList(string prefixText)
{
BDBEntities db = new BDBEntities();
List<SearchBean> lstfinaldata = new List<SearchBean>();
List<MaCatMaster> lstcatlist = db.MaCatMasters.Where(z => z.CatName.Contains(prefixText) && z.Status == true).ToList();
foreach (MaCatMaster obj in lstcatlist)
{
SearchBean objbean = new SearchBean();
objbean.Id = obj.Id;
objbean.Title = obj.CatName;
objbean.stype = "Category";
objbean.reUrl = www.demo.com + "/Pages/Coupons/" + obj.Id;
lstfinaldata.Add(objbean);
}
string[] st = new string[lstfinaldata.Count];
int i = 0;
foreach (SearchBean obj in lstfinaldata)
{
StringBuilder sb = new StringBuilder();
sb.Append("<html><body>");
sb.AppendFormat("<a href='{0}' name='urllink'>", obj.reUrl);
sb.Append("<table width='420px'>");
sb.AppendFormat("<tr><td width='60px'><img src='{0}' style='border:1px solid #eeeeee' width='60px' height='40px'></td><td align='left' width='300px'>{1}</td><td align='left' width='60px' style='font-size:14px;'>{2}</td></tr>", obj.photoAdd, obj.Title, obj.stype);
sb.Append("</table>");
sb.Append("</a>");
sb.Append("</body></html>");
st[i] = sb.ToString();
i++;
}
return st;
}
In your search method you can use AutoCompleteExtender.CreateAutoCompleteItem() method to create pairs of the text to display and the image path:
public static List<string> Search(string prefixText, int count)
{
var items = new List<string>();
// ...
items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(
text,
imagePath));
// ...
return items;
}
Then create the img tags on the client side with a javascript:
function Items_Populated(sender, e) {
var items = sender.get_completionList().childNodes;
for (var i = 0; i < items.length; i++) {
var div = document.createElement(“div”);
div.innerHTML = ”<img src=' + items[i]._value + ’ /><br />”;
items[i].appendChild(div);
}
Here are some examples:
AJAX AutoComplete with prefix image
Auto Complete with images