I am passing a collection of values through ajax, then i can not able to retrieve these values from webmethod by foreach procedure.
my collection variable is var Leave = { "Date": [], "Half": [] };
Passing Leave to webmethod but it is not possible to retrieve values
.pls help me.
my code is
empid = document.getElementById("hdnemployee").value;
if (empid != "") {
var Leave = { "Date": [], "Half": [] };
$('.leave_item').each(function () {
var cur = $(this);
var thisdate = cur.find('.txtdate').val();
Leave.Date.push(thisdate);
if (cur.find('.ckbhalfday').is(':checked'))
Leave.Half.push(1);
else
Leave.Half.push(0);
});
var arr = new Array();
console.log(Leave);
arr[0] = document.getElementById('drpLeavetype').value;
//arr[1] = document.getElementById('TxtDatefrom').value;
//arr[2] = document.getElementById('TxtDateTo').value;
arr[3] = document.getElementById('Txtnumdays').value;
arr[4] = document.getElementById('txtDiscription').value;
if (arr[4] != "")
{
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "Applyleave.aspx/saveleaveApply",
data: JSON.stringify({ empid: empid,Leave:Leave, arr: arr }),
success: function (msg) {
// document.getElementById("tblleaveapply").innerHTML = "";
$('#tblleaveapply').empty();
alert(msg.d);
resettxtfields();
BindLADetails();
},
error: function (msg) { alert(msg.d); }
});
}
else
{
alert("Give Reason");
}
}
else {
alert("Select employee");
}
WebMethod:-
[WebMethod]
public static string saveleaveApply(string empid, object Leave, params string[] arr)
{
foreach( var c in Leave)
{
}
}
You can't use a foreach statement on an object unless it implements IEnumerable or IEnumerable<T> interface. What you need to do is define a Type in your code behind which will map to the JSON object something like this:-
public class Leave
{
public string[] Date { get; set; }
public string[] Half { get; set; }
}
Then you can modify your WebMethod as follows and iterate over the items:-
[WebMethod]
public static string saveleaveApply(string empid, Leave Leave, params string[] arr)
{
foreach( var c in Leave.Date)
{
}
foreach( var c in Leave.Half)
{
}
}
Update:
Although, I personally won't use this type, instead I will use:-
public class Leave
{
public string Date { get; set; }
public string Half { get; set; }
}
You need to fill this type in JS like this:-
var leave = new Array();
$('.leave_item').each(function() {
var cur = $(this);
var thisdate = cur.find('.txtdate').val();
var thishalf;
if (cur.find('.ckbhalfday').is(':checked'))
thishalf = 1;
else
thishalf = 0;
leave.push({ "Date": thisdate, "Half": thishalf });
});
And Finally the WebMethod will look like this:-
[WebMethod]
public static string saveleaveApply(string empid, Leave[] Leave, params string[] arr)
{
foreach( var c in Leave)
{
}
}
Related
I am working on two web method And I want to access one filed from another web Method and I am not sure how can it will be possible.
I want to call DivisionCode in another web method is it possible ?
WebMethod1 Getcompanies :
From this web method i want to get DivisionCode = company.DivisionCode and will pass into another web method as a parameter
[WebMethod]
public static List<Company> Getcompanies(string Countrycode, string Companycode)
{
GetInitiatorList.MasterDataServiceClient oClient = new GetInitiatorList.MasterDataServiceClient();
Almarai.GiveAway.GetInitiatorList.ALM_COMPANY_M[] initiatorslist = oClient.GetCompanies(Countrycode, Companycode);
//almarai.giveaway.getinitiatorlist.alm_company_m[] companymlist = initiatorslist.companies;
List<Company> companyes = new List<Company>();
foreach (Almarai.GiveAway.GetInitiatorList.ALM_COMPANY_M company in initiatorslist)
{
companyes.Add(new Company()
{
CompanyCode = company.CompanyCode,
CompanyName = company.CompanyName,
DivisionCode = company.DivisionCode
});
}
return companyes;
}
Respected class:
public class Company
{
public string CompanyCode { get; set; }
public string CompanyName { get; set; }
public string DivisionCode { get; set; }
}
WebMethod 2 GetDivision
This is my second web Method and i want to pass FirsrWebMethod field to another web method ( DivisionCode = company.DivisionCode )
[WebMethod]
public static List<Devision> GetDivision(string Countrycode, string Companycode)
{
string Divisi = string.Empty;
var v = new Company();
v.DivisionCode = Divisi; //v.DivisionCode returning "" (Empty string)
GetInitiatorList.MasterDataServiceClient oClient = new GetInitiatorList.MasterDataServiceClient();
// Almarai.GiveAway.GetInitiatorList.INITIATORS_LIST initiatorsList = oClient.GetInitiatorsListByWorkflow(userid, work);
Almarai.GiveAway.GetInitiatorList.ALM_DIVISION_M[] divisionMList = oClient.GetActiveDivisions(Countrycode, Companycode, Divisi) ;
//GetActiveDivisions Expecting three parameters including divisionCode
List<Devision> Division = new List<Devision>();
foreach (Almarai.GiveAway.GetInitiatorList.ALM_DIVISION_M Devision in divisionMList)
{
Division.Add(new Devision()
{
DevisionCode = Devision.DivisionCode,
DevisionName = Devision.DivisionName
});
}
return Division;
}
Respected Class:
public class Devision
{
public string DevisionCode { get; set; }
public string DevisionName { get; set; }
}
JS
$('#ddlCompany').change(function (e) {
BindDivision();
});
BindCompanies:
function BindCompanies() {
var countrycode = $('#ddlCountry').val();
$('#ddlCompany').empty();
if (countrycode == 'OMN') {
Companycode = '7000';
}
else if (countrycode == 'SAU') {
Companycode = '1000';
}
else if (countrycode == 'UAE') {
Companycode = '5000';
}
else if (countrycode == 'BAH') {
Companycode = '4000';
}
else if (countrycode == 'KWT') {
Companycode = '6000';
}
$.ajax({
type: "POST",
url: "Header.aspx/Getcompanies",
data: JSON.stringify({ Countrycode: countrycode, Companycode: Companycode }),
dataType: "json",
contentType: "application/json",
success: function (res) {
$.each(res.d, function (data, value) {
$("#ddlCompany").append($("<option></option>").val(value.CompanyCode).html(value.CompanyName));
});
}
});
}
BindDivision: (Bind Division method requires three Parameter 1. CompanyCode, 2. CountryCode, 3. DivisionCode)
I can able to pass only two parameters (CompanyCode, CountryCode)
But not sure how to Pass DivisionCode. (I know GetCompany Method returning three parameter and i am binding company drop down using CompanyCode and CompanyName But what about DivisionCode)Because where should I store DivisionCode field
function BindDivision() {
//var DivisionCode = Not sure how to pass
var companycode = $('#ddlCompany').val();
var countrycode = $('#ddlCountry').val();
$('#ddlDivision').empty();
$.ajax({
type: "POST",
url: "Header.aspx/GetDivision",
data: JSON.stringify({ Countrycode: countrycode, Companycode: companycode }),
dataType: "json",
contentType: "application/json",
success: function (res) {
$.each(res.d, function (data, value) {
$("#ddlDivision").append($("<option></option>").val(value.DevisionCode).html(value.DevisionName));
});
}
});
}
In my AJAX method i am passing two parameter from selected drop down list and i want to pass another parameter that is DivisionCode from One WebMethod to another Webmethod.
Probly we can pass from AJAX but how can i store In ASPX (DevisionCode is not singe value it is list as you can see i am storing thoes value in List only)
Please help me
I am working on e-commerce site. I want to filter product based on multiple check boxes. I use ajax. It sends check boxes' IDs to the controller. But selected counts zero like in the picture. What is wrong with this code?
Ajax:
<script type="text/javascript">
$(function () {
$('.filterprod').click(function () {
var ProdID = "";
$('.checks').each(function () {
if ($(this).is(':checked')) {
ProdID += $(this).val() + ",";
}
});
var data = {};
data.Id = ProdID.slice(0, ProdID.length - 1);
$.ajax({
url: '/Shop/GetProd',
method: 'POST',
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(data),
success: function (response) {
$("#Prodlist").remove();
},
error: function (err, response) {
console.log(err, response);
alert(err, response.responseText);
}
})
});
});
</script>
Controller:
[HttpPost]
public JsonResult GetProd(string Id)
{
var ids = new List<int>();
IQueryable<Product> prods = null;
if (!string.IsNullOrEmpty(Id))
{
for (int i = 0; i < Id.Split(',').Length; i++)
{
ids.Add(Convert.ToInt32(Id.Split(',')[i]));
}
prods =_context.Products.Where(t => ids.Contains(t.id));
}
else
{
prods = _context.Products.Take(5);
}
var selected = (from v in prods
select new
{
v.ProdName,
v.Price,
v.Description
}).ToList();
return Json(selected, JsonRequestBehavior.AllowGet);
}
Try to do it in a console like this: https://dotnetfiddle.net/AMwxiP
using System;
using System.Collections.Generic;
using System.Linq;
public class Product
{
public int Id { get; set; }
public string ProdName { get; set; }
public decimal? Price { get; set; }
public string Description { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
IQueryable<Product> products = (new List<Product> {
new Product
{
Id = 1,
},
new Product
{
Id = 2,
}
}).AsQueryable<Product>();
var Id = "1,2";
var ids = new List<int>();
IQueryable<Product> prods = null;
if (!string.IsNullOrEmpty(Id))
{
for (int i = 0; i < Id.Split(',').Length; i++)
{
ids.Add(Convert.ToInt32(Id.Split(',')[i]));
}
prods = products.Where(t => ids.Contains(t.Id));
}
else
{
prods = products.Take(5);
}
var selected = (from v in prods
select new
{
v.ProdName,
v.Price,
v.Description
}).ToList();
Console.WriteLine(selected.Count);
}
}
I'm attempting to do server-side processing of jQuery DataTables using ASP.NET MVC with Entity Framework. I came across Datatables.AspNet Nuget package, but I'm unclear how to use it to dynamically sort columns when clicked on table headers.
In an example on Datatables.AspNet GitHub, there is this:
public ActionResult PageData(IDataTablesRequest request)
{
var data = Models.SampleEntity.GetSampleData();
var filteredData = data.Where(_item => _item.Name.Contains(request.Search.Value));
// Paging filtered data.
var dataPage = filteredData.Skip(request.Start).Take(request.Length);
var response = DataTablesResponse.Create(request, data.Count(), filteredData.Count(), dataPage);
return new DataTablesJsonResult(response, JsonRequestBehavior.AllowGet);
}
But I'm unsure how to proceed to dynamically sort based on the contents of the IDataTablesRequest object, which looks like this:
public interface IDataTablesRequest
{
int Draw { get; }
int Start { get; }
int Length { get; }
ISearch Search { get; }
IEnumerable<IColumn> Columns { get; }
IDictionary<string, object> AdditionalParameters { get; }
}
public interface ISort
{
int Order { get; }
SortDirection Direction { get; }
}
public enum SortDirection
{
Ascending = 0,
Descending = 1
}
take a look at this answer: https://github.com/ALMMa/datatables.aspnet/issues/26
for reference:
public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, IEnumerable<DataTables.AspNet.Core.IColumn> sortModels)
{
var expression = source.Expression;
int count = 0;
foreach (var item in sortModels)
{
var parameter = Expression.Parameter(typeof(T), "x");
var selector = Expression.PropertyOrField(parameter, item.Field);
var method = item.Sort.Direction == DataTables.AspNet.Core.SortDirection.Descending ?
(count == 0 ? "OrderByDescending" : "ThenByDescending") :
(count == 0 ? "OrderBy" : "ThenBy");
expression = Expression.Call(typeof(Queryable), method,
new Type[] { source.ElementType, selector.Type },
expression, Expression.Quote(Expression.Lambda(selector, parameter)));
count++;
}
return count > 0 ? source.Provider.CreateQuery<T>(expression) : source;
}
so you can do the following:
var orderColums = request.Columns.Where(x => x.Sort != null);
var dataPage = data.OrderBy(orderColums).Skip(request.Start).Take(request.Length);
I know this is late answer but for anyone interested.... using Datatable on Asp .NET Core
here YOURMODEL: should be the same type
public IEnumerable<YOURMODEL> SortDataByColumn(IEnumerable<YOURMODEL> data, IDataTablesRequest request){
var sortColumn = request.Columns.FirstOrDefault(s => s.Sort != null);
if(sortColumn == null) return data;
if (sortColumn.Sort.Direction == SortDirection.Descending)
{
return data.OrderByDescending(c => c.GetType().GetProperty(sortColumn.Field).GetValue(c));
}
return data.OrderBy(c => c.GetType().GetProperty(sortColumn.Field).GetValue(c));
}
FYI..This assumes a sort on a single column.....
// c#
public class JQueryDataTableParamModel
{
public Int32 start { get; set; }
public Int32 length { get; set; }
public JQueryDataTableOrder[] order { get; set; }
public class JQueryDataTableOrder
{
public Int32 column { get; set; }
public String dir { get; set; }
}
}
MyFunctionName: function (tableId)
{
$(tableId).DataTable({
serverSide: true,
processing: true,
deferRender: true,
"bPaginate": true,
"bLengthChange": false,
"bFilter": false,
"bInfo": true,
"bAutoWidth": true,
"ordering": true,
"bSortClasses": false,
"bDestroy": true,
bLengthChange: false,
"iDisplayLength": 50,
responsive: true,
dom: 'Bfrtip',
ajax: function (data, callback, s) {
var parms = {
start: data.start,
length: data.length,
order[{column:data.order[0].column,dir:data.order[0].dir}],
addtionalParam: $('#IdOfTheTextBox').val(),
}
ajax =
$.ajax({
url: '/AreaName/ControllerName/Method',
type: "POST",
contentType: "application/json",
dataType: 'json',
data: JSON.stringify(parms),
success: function (data) { callback(data); },
error: function (e) {
// can add sweetalert or normal alert
}
});
},
aoColumns: [
{
sName: "Name",
render: function (a, b, c) {
return '<td>' + a + '</td>'
}
},
{
sName: "Surname",
render: function (a, b, c) { return '<td>' + a + '</td>' }
},
{
sName: "Id",
"bSortable": false,
sClass: "action",
render: function (a, b, c) {
return "This will be your button(s)"
}
}
]
});
}
public JsonResult MethodSignature(string additionalParam, JQueryDataTableParamModel param)
{
var myList= GetYourList();
if (param.order[0].dir == "asc")
myList= myList.OrderBy(x=>x.Name);
else
myList= myList.OrderByDescending(x=>x.Name);
var dataToReturn= sm.Skip(param.start).Take(param.length).ToList().Select(x
=> new object[]
{
x.Name,
x.Surname,
x.Id
});
return Json(new
{
iTotalRecords = myList.Count(),
iTotalDisplayRecords = myList.Count(),
aaData = dataToReturn,
}, JsonRequestBehavior.AllowGet);
}
function myItemsViewModel(ItemID, GroupID, ItemName, Quantity) {
this.ItemID = ItemID;
this.GroupID = GroupID;
this.ItemName = ItemName;
this.Quantity = Quantity;
}
And i have below code for posting to the controller
var CreateRecord = function () {
var Name = $.trim($("#divCreate").find("#txtName").val());
var Department = $.trim($("#divCreate").find("#txtDepartment").val());
var ItemsList = [];
$('#myDynamicTable').find('tr').each(function () {
var row = $(this);
var itemName = $.trim(row.find(".itemName input").val());
var itemQty = $.trim(row.find(".itemQty input").val());
var myItems = new myItemsViewModel("", "", itemName, itemQty);
ItemsList.push(myItems);
});
var obj = new myRecordEntryViewModel("", Name, Department, ItemsList);
var viewmodel = JSON.stringify(obj);
$.ajax({
type: 'POST',
cache: false,
dataType: 'html',
data: viewmodel,
headers: GetRequestVerificationToken(),
contentType: 'application/json; charset=utf-8',
url: '/' + virtualDirectory + '/RecordEntry/Save',
success: function (data) {
$("#divMaster").html(data);
return false;
},
error: function (msg) {
alert("Error Submitting Record Request!");
}
});
}
At the line var viewmodel = JSON.stringify(obj);, viewmodel has all the values that i want in my ItemsList array variable.
Problem is my ItemsList array is coming as null in the controller. Name and Department are coming through with the correct passed values.
Below is my controller code.
Class
public class myRecordEntryViewModel
{
public long ID { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public string[] ItemsList { get; set; }
}
Save action
[ActionName("Save")]
[NoCache]
public ActionResult Save(myRecordEntryViewModel viewModel)
{
//here viewModel.ItemsList is null, what could i be missing
if (this.SaveEntry(viewModel.Name,viewModel.Department,viewModel.ItemsList))
{
}
return this.View();
}
I'm wondering why viewModel.ItemsList is coming as null in controller yet it has values during the post from jQuery.
You should create a class for the Item in Item List (In C#)
public class Item {
public string ItemName { get; set; }
public int Quantity { get; set; }
}
And then change the viewmodel class
public class myRecordEntryViewModel
{
public long ID { get; set; }
public string Name { get; set; }
public string Department { get; set; }
//public string[] ItemsList { get; set; }
public List<Item> ItemsList {get ; set;}
}
The controller can not map the Item List from your request into model because one is a list of string and other is a list of object.
There are several problems in your codes...
1) ItemList in your class and your javascript code are not same - The frist one is an array of strings, and the second is an array of objects
2) In your action method, you should change parameter type like the following:
public ActionResult Save(string viewModel)
3) In the body of your action method, you should deserialize the json string (viewModel) and make the model object from it. The following is an example...
https://stackoverflow.com/a/17741421/1814343
Try the below code and see if your model gets the values.
Let me know if you face any problems, because I've already implemented this in one of my projects
var CreateRecord = function () {
var Name = $.trim($("#divCreate").find("#txtName").val());
var Department = $.trim($("#divCreate").find("#txtDepartment").val());
var model="";
var ItemsList = [];
$('#myDynamicTable').find('tr').each(function () {
var row = $(this);
var itemName = $.trim(row.find(".itemName input").val());
var itemQty = $.trim(row.find(".itemQty input").val());
var myItems = new myItemsViewModel("", "", itemName, itemQty);
ItemsList.push(myItems);
});
model = ['Name' : Name , 'Department' : Department , 'ItemsList' :ItemsList];
$.ajax({
type: 'POST',
cache: false,
dataType: 'html',
data: JSON.stringify(model),
headers: GetRequestVerificationToken(),
contentType: 'application/json; charset=utf-8',
url: '/' + virtualDirectory + '/RecordEntry/Save',
success: function (data) {
$("#divMaster").html(data);
HideLoader();
return false;
},
error: function (msg) {
alert("Error Submitting Record Request!");
HideLoader();
}
});
}
I need some help with my web service and json call.. stuck trying to get the data returned, I've done this successful with strings and objects.. but not an array...
My Web Service Contains:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetSearchCriteria()
{
var js = new JavaScriptSerializer();
var obj = HttpContext.Current.Session["mysessionname"];
if (obj == null)
{
var result = new Criteria[]
{
new Criteria() { Key = Guid.NewGuid(), Operator = "=", ColumnName = "CheckID", Value = "" }
};
var serial = js.Serialize(result);
return serial;
}
else
{
var serial = js.Serialize((Criteria[])obj);
return serial;
}
}
Criteria is:
[Serializable]
public class Criteria
{
public Guid Key { get; set; }
public string ColumnName { get; set; }
public string Operator { get; set; }
public string Value { get; set; }
}
My Page Contains:
<script type="text/javascript">
function RefreshCriteria() {
$.ajax({
type: 'POST',
url: '<%= System.Web.VirtualPathUtility.ToAbsolute("~/Services/WebService.asmx/GetSearchCriteria") %>',
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Content-type",
"application/json; charset=utf-8");
},
success: function (data) {
$(data).each(function (i) {
var obj = data[i];
alert(obj);
});
}
});
}
$(document).ready(function () {
RefreshCriteria();
});
</script>
What I'm getting is undefined every time.. tried doing
$(data).each(function (i) {
var obj = data[i];
alert(obj);
});
$(data).each(function (i, obj) {
alert(obj);
});
$(data).each(function (i) {
alert(this);
});
None worked so far..
you can tighten up the ajax
$.ajax({
type: 'POST',
url: '*you need a url here*',
dataType: 'json',
success: function (data) {
$(data).each(function (index, item) {
console.log(item);
});
}
});
next using either firebug or fiddler monitor the request/response to ensure what you are sending and receiving is what you expected.