Add multiple records setting properties using an index - c#

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);;
}
});

Related

How to access an array retrieved from controller via AJAX

I call an MVC controller via Java and AJAX. The data goes to the controller, the controller returns a List. How do I access that list? This may seem trivial, but I can't find it anywhere on google or SO. Most of the examples I've found call for using:
...
success: function (r) {
var exemptions = r.d;
...
for (var i = 0; i < exemptions.length; i++){
ddlist.appent('<option>' + exemptions[i] + '</option>');
....
}
That method, however, results in this error:
Uncaught TypeError: Cannot read property 'length' of undefined
at Object.success (6:281)
at u (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at k (jquery.min.js:2)
at XMLHttpRequest.<anonymous> (jquery.min.js:2)
Controller Method:
public JsonResult GetValidRecords(int year)
{
var items = new List<SelectListItem>();
var Exemptions = model.Permits.Where(m => m.Year == year).OrderBy(m => m.Exemption).OrderBy(m => m.Year).ToList();
foreach (Permit x in Exemptions)
{
items.Insert(items.Count, new SelectListItem { Text = x.Exemption.ToString(), Value = x.Exemption.ToString() });
}
return Json(items, JsonRequestBehavior.AllowGet);
}
The dropdown box:
<text>EXEMPTION RENEWAL FORM</text>
<select id="dd" name="dd" onchange="CallRenewalReport(this.value)">
<option value="">Select Year First</option>
</select>
#Html.DropDownList("ddldate", new SelectList(Model.RYearList, "ID", "Year", "Select a year"), new { #onchange = "GetGoodRecords(this.value)", #AppendDataBoundItems = "False" })
break;
The JavaScript/AJAX query:
<script type="text/javascript">
function GetGoodRecords(val) {
alert(val);
var year = val;
var RootUrl = '#Url.Content("~/")';
$.ajax({
url: RootUrl + "Reports/GetValidRecords",
data: { year: year },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var exemptions = response.d;
var ddlist = $('#dd');
ddlist.empty().append('<option selected="selected" value="0">Select Exemption</option>');
for (var i = 0; i < exemptions.length; i++) {
ddlist.append('<option>' + exemptions[i] + '</option>');
}
}
});
};
</script>
Can anyone spell this out to me in layman's terms?
Regards,
Carthax
Give this a shot in your success function:
success: function (response) {
for (var i = 0; i < response.length; i++) {
var obj = JSON.parse(JSON.stringify(response[i]));
alert(obj.Text);
}
}
This will show an alert of what is contained in each object of the response array.
(In case someone happens upon this question in google)
Based on input from #MikeMarshall, here is the solution that works:
The controller action is correct, but I'm putting it all in one place so you don't have to copy-and-paste from all over the page
public JsonResult GetValidRecords(int year)
{
var items = new List<SelectListItem>();
var Exemptions = model.Permits.Where(m => m.Year == year).OrderBy(m => m.Exemption).OrderBy(m => m.Year).ToList();
foreach (Permit x in Exemptions)
{
items.Insert(items.Count, new SelectListItem { Text = x.Exemption.ToString(), Value = x.Exemption.ToString() });
}
return Json(items, JsonRequestBehavior.AllowGet);
}
The razor code:
<text>EXEMPTION RENEWAL FORM</text>
<select id="dd" name="dd" onchange="CallRenewalReport(this.value)">
<option value="">Select Year First</option>
</select>
#Html.DropDownList("ddldate", new SelectList(Model.RYearList, "ID", "Year", "Select a year"), new { #onchange = "GetRecords(this.value)", #AppendDataBoundItems = "False" })
break;
The script:
<script type="text/javascript">
function GetRecords(val) {
alert(val);
var year = val;
var RootUrl = '#Url.Content("~/")';
$.ajax({
url: RootUrl + "Reports/GetValidRecords",
data: { year: year },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// get the dropdownlist
var ddlist = $('#dd');
// empty the dropdownlist and add "Select Exemption"
ddlist.empty().append('<option selected="selected" value="0">Select Exemption</option>');
// for each value in the response
for (var i = 0; i < response.length; i++) {
// properly query the Value and Text fields in the array
ddlist.append('<option value="' + response[i].Value + '">' + response[i].Text + '</option>');
}
}
});
};
</script>

search mvc json jquery

I'm having trouble with auto-search when I want to make two values
I want to search the store for product, please guide:
Controller
public JsonResult Search(string pr, string name, string model, string brand, string storename) {
var s = _context.Products.Where(a => a.Name.Contains(pr) || a.Model.Contains(pr) || a.Brands.Name.Contains(pr)).Select(a => new {
name = a.Name, model = a.Model, brand = a.Brands.Name
}).Take(10);
var storen = _context.Stores.Where(a => a.Name.StartsWith(pr)).Select(a => new {
storename = a.Name
});
return Json(new {
s,
storen
}, JsonRequestBehavior.AllowGet);
}
View
$(document).ready(function () {
var kam;
$("#CityName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/search",
type: "POST",
dataType: "json",
data: {
pr: request.term
},
success: function (data) {
response($.map(data, function (item) {
return [{
label: item.name + " " + item.model + " " + item.brand,
value: item.name + " " + item.model + " " + item.brand
}]
}))
}
})
},
messages: {
noResults: "",
results: ""
}
});
})
I think you want to combine both result sets to show into one Autocomplete widget. So for that, try to modify your code to look like this
Controller
public JsonResult Search(string pr) {
var s = _context.Products.Where(a => a.Name.Contains(pr) || a.Model.Contains(pr) || a.Brands.Name.Contains(pr)).Take(10).Select(a => new {
resultItem = a.Name + " " + a.Model + " " + a.Brands.Name
}).ToList();
var storen = _context.Stores.Where(a => a.Name.StartsWith(pr)).Select(a => new {
resultItem = a.Name
}).ToList();
var returnList = s.Concat(storen).ToList();
return Json(new {
returnList
}, JsonRequestBehavior.AllowGet);
}
This way your controller returns only one result set in json format.
View
$(document).ready(function () {
$("#CityName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/Search",
type: "GET",
dataType: "json",
data: {
pr: request.term
},
success: function (data) {
response($.map(data, function (item) {
return [{
label: item.resultItem,
value: item.resultItem
}]
}))
}
})
},
messages: {
noResults: "",
results: ""
}
});
})
Note that I have changed the ajax request type to GET and label and value use the same resultItem field.
Instaed of:
var storen = _context
.Stores
.Where(a => a.Name.StartsWith(pr))
.Select(a => new { storename = a.Name });
Don't you want to use Contains, like in the first query ?
var storen = _context
.Stores
.Where(a => a.Name.Contains(pr))
.Select(a => new { storename = a.Name });

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.

Internal server error in ajax post request

Guys I have problem with my ajax post request and it is not working for some dates i.e it does not hits controller but for some dates it works fine please help me to find out the bug
Here is my code
$("#getInfo").click(function ()
{
var elementValue = document.getElementById("tournamentID").value;
var startDateValue = document.getElementById("filterDateStartnew").value;
if (elementValue == null || elementValue == "" || startDateValue == null || startDateValue == "")
{
alert("please enter TournamentID and timestamp to get Info");
return false;
}
$.ajax({
type: "POST",
cache: false,
url: '/reports/gettournamentinfo',
data: { tournamentID: elementValue,date: startDateValue },
success: function (data)
{
var select = document.getElementById("TournamentLevel");
var length = select.options.length;
//Delete All Options
$('#TournamentLevel')
.find('option')
.remove()
.end()
var opt = document.createElement("option");
opt.text = "Any";
opt.value = -1;
document.getElementById("TournamentLevel").options.add(opt);
var count = data[0];
for (var i = 1; i <= count; i++)
{
var opt = document.createElement("option");
opt.text = i;
opt.value = i;
document.getElementById("TournamentLevel").options.add(opt);
}
for (var index = 1; index < data.length; ++index)
{
var opt = document.createElement("option");
opt.text = data[index];
opt.value = data[index];
document.getElementById("RunID").options.add(opt);
}
$("#SubmitForm").removeAttr('disabled');
},
error: function(data)
{
alert("there was no info for that tournamentID and that date");
$.unblockUI();
$('#TournamentLevel')
.find('option')
.remove()
.end()
return false;
}
});
return false;
});
Check for the data formats. For example if the client using dd/mm/yyyy and the server is expecting mm/dd/yyyy, you will see a HTTP 500 error as the model binder will fail to do the binding
Change your ajax post method like below.
$.ajax({ url: "/reports/gettournamentinfo", contentType: "application/json; charset=utf-8", type: "POST",
data: '{"tournamentID":"' + elementValue+ '", "date":"' + startDateValue + '"}',
success: function (data) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) { }
});

Categories