Ajax call not reach to server side methods? - c#

When i click on button it will call JavaScript method after that on Ajax call if i debug it on Firefox browser than it calls server side method setMandate() but not directly on button click, i don't know what is happening?
<div>
<button id="GetMandateBtn" onclick="SetMandate()" disabled>Get Mandate</button>
</div>
function SetMandate() {
var clients = new Array();
var queryNo = 0;
$("#DivMandateClients input:checked").each(function () {
clients.push($(this).attr('value'));
});
if (clients == "")
clients.push(0);
var contacts = new Array();
$("#DivMandateClientsContact input:checked").each(function () {
contacts.push($(this).attr('value'));
var value = $(this).val();
});
if (contacts == "")
contacts.push(0);
var candidateStatus = new Array();
$("#candidateStatus input:checked").each(function () {
candidateStatus.push($(this).attr('value'));
});
if (candidateStatus == "") {
candidateStatus.push(0);
queryNo = 0;
}
var mandateRegion = new Array();
$("#MandateRegion input:checked").each(function () {
mandateRegion.push($(this).attr('value'));
});
if (mandateRegion == "") {
mandateRegion.push(0);
queryNo = 0;
}
var mandateCountry = new Array();
$("#MandateCountry input:checked").each(function () {
mandateCountry.push($(this).attr('value'));
});
if (mandateCountry == "") {
mandateCountry.push(0);
queryNo = 0;
}
var researchers = new Array();
$("#Researcher input:checked").each(function () {
researchers.push($(this).attr('value'));
});
if (researchers == "") {
researchers.push(0);
queryNo = 0;
}
if (StartDateTxt.value.trim() != "" && EndDateTxt.value.trim() != "") {
$.ajax({
url: "/WebService/GetMandate",
data: "{ 'startDate' : '" + StartDateTxt.value + "','endDate' : '" + EndDateTxt.value + "','clients' : '" + clients + "','contacts' : '" + contacts + "','candidateStatus' : '" + candidateStatus + "','mandateRegion' : '" + mandateRegion + "','mandateCountry' : '" + mandateCountry + "','researchers' : '" + researchers + "','queryNo' : '" + queryNo + "'}",
dataType: "json",
type: "POST",
dataFilter: function (data) { return data; },
success: function (data) {
var mandate = $("#Mandate");
mandate.html("");
if (data != null) {
if (data != "")
mandate.append($("<input type='checkbox' id='chklstMandate-2' name='Mandate' value='-2'/> <label style='display:inline;' id='lblMandate-2'>Select All</label><hr/>"));
$.each(data, function (index, value) {
mandate.append($("<input type='checkbox' id='chklstMandate" + data[index].ResearcherId + "' name='Mandate' value='" + data[index].ResearcherId + "'/> <label style='display:inline;' id='lblMandate" + data[index].ResearcherId + "'>" + data[index].MandaName + "</label><br />"));
});
$("#chklstMandate-2").click(function (event) {
if ($("#chklstMandate-2").is(":checked"))
$("#Mandate").each(function () {
$("input[type=checkbox][name='Mandate']").attr("checked", true);
});
else if ($("#chklstMandate-2").not(":checked"))
$("#Mandate").each(function () {
$("input[type=checkbox][name='Mandate']").attr("checked", false);
});
});
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error on Loading Mandate" + errorThrown);
}
});
}
};
public ActionResult GetMandate()
{
// InputStream contains the JSON object you've sent
String jsonString = new StreamReader(this.Request.InputStream).ReadToEnd();
// Deserialize it to a dictionary
var dic = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<String, string>>(jsonString);
var startDate = Convert.ToDateTime(dic["startDate"]);//DateTime.Parse(dic["startDate"]);
var endDate = DateTime.Parse(dic["endDate"]);
string[] clients = dic["clients"].Split(',');
string[] contacts = dic["contacts"].Split(',');
string[] candidateStatus = dic["candidateStatus"].Split(',');
string[] mandateRegion = dic["mandateRegion"].Split(',');
string[] mandateCountry = dic["mandateCountry"].Split(',');
string[] researchers = dic["researchers"].Split(',');
int queryNo = int.Parse(dic["queryNo"]);
//bool isClientIdSelected = true;
List<int> clientIds = new List<int>();
foreach (var clnt in clients)
{
if (clnt != "-2" && clnt != "0")
clientIds.Add(int.Parse(clnt));
}
List<int> contactIds = new List<int>();
foreach (var conts in contacts)
{
if (conts != "-2" && conts != "0")
contactIds.Add(int.Parse(conts));
}
List<int> candidateStatusIds = new List<int>();
foreach (var status in candidateStatus)
{
if (status != "-2" && status != "0")
candidateStatusIds.Add(int.Parse(status));
}
List<int> mandateRegionIds = new List<int>();
foreach (var region in mandateRegion)
{
if (region != "-2" && region != "0")
mandateRegionIds.Add(int.Parse(region));
}
List<int> mandateCountryIds = new List<int>();
foreach (var country in mandateCountry)
{
if (country != "-2" && country != "0")
mandateCountryIds.Add(int.Parse(country));
}
List<int> researcherIds = new List<int>();
foreach (var researcher in researchers)
{
if (researcher != "-2" && researcher != "0")
researcherIds.Add(int.Parse(researcher));
}
if (queryNo == 0)
{
var mandaetFromDB = (from mc in dbContext.MandateCandidates
join m in dbContext.Mandates on mc.MandateId equals m.MandateId
join mr in dbContext.MandateResearchers on mc.MandateId equals mr.MandateId
where m.StartDate >= startDate
&& m.EndDate <= endDate
&& clientIds.Contains(m.ClientId)
&& contactIds.Contains(m.ContactId)
&& candidateStatusIds.Contains(mc.CandidateStatusId ?? 0)
select new { MandateId = m.MandateId, MandaName = m.Name, ResearcherId = mr.ResearcherId, ClientId = m.ClientId }).ToList();
return Json(mandaetFromDB, JsonRequestBehavior.AllowGet);
}
else
{
var mandaetFromDB = (from mc in dbContext.MandateCandidates
join m in dbContext.Mandates on mc.MandateId equals m.MandateId
join mr in dbContext.MandateResearchers on mc.MandateId equals mr.MandateId
where m.StartDate >= startDate
&& m.EndDate <= endDate
&& clientIds.Contains(m.ClientId)
&& contactIds.Contains(m.ContactId)
&& candidateStatusIds.Contains(mc.CandidateStatusId ?? 0)
&& mandateRegionIds.Contains(m.RegionId ?? 0)
&& mandateCountryIds.Contains(m.MandateCountryId ?? 0)
&& researcherIds.Contains(mr.ResearcherId ?? 0)
select new { MandateId = m.MandateId, MandaName = m.Name, ResearcherId = mr.ResearcherId, ClientId = m.ClientId }).ToList();
return Json(mandaetFromDB, JsonRequestBehavior.AllowGet);
}
//return Json(mandaetFromDB, JsonRequestBehavior.AllowGet);
}

Related

Ajax.BeginForm model binding fails with SelectElement,Onchange

I'm experiencing an odd issue .
I got both a text input search field, and a dropdown list.
I've set that with every change on the select menu it will submit said form with the values .
It does bind the values but it bypasses the OnSuccess function and then basically things fall apart
Relevant Code:
#Html.EnumDropDownListFor(x => x.AreaCodes, "בחר אזור", new
{
#class = "select_field w-select",
onchange = "this.form.submit()"
})
ReloadLocations = () => {
$.ajax({
url:`#Url.Action("LocationsList","Locations")`,
method: 'POST',
dataType: 'html',
contentType: 'charset=utf-8',
success: function (data) {
$("#LocationList").empty();
$("#LocationList").append(data);
},
In this version it submits the form, However it goes straight to the function without actually going into the "success" part of the ajax call,
Just returns a view.
which results in me getting a partial view back.
How can I fix this?
Edit:
Full Controller Methode:
{
public ActionResult LocationsList(SearchLocationVM searchVm)
var locationsVM = new List<LocationVM>();
var locations = new List<Locations>();
var searchTerm = searchVm.SearchTerm;
var searchArea = (int)searchVm.AreaCodes;
using (var unitOfWork = new UnitOfWork(new FriendsEntities()))
{
if (searchVm.AreaCodes == 0 && string.IsNullOrWhiteSpace(searchVm.SearchTerm))
{
locations = unitOfWork.Locations.Find(x => x.Visibility).OrderBy(x => x.Order).ToList();
locationsVM = locations.Select(x => new LocationVM()
{
ActivityHours = x.location_open_time ?? string.Empty,
ContactName = x.location_contact_name ?? string.Empty,
FirstPHone = x.first_phone_number ?? string.Empty,
SecondPHone = x.second_phone_number ?? string.Empty,
IsRefrigirated = x.location_refrigerated_medication,
LocationAdress = x.location_address ?? string.Empty,
LocationAreaName = x.location_general_area ?? string.Empty,
WhatsappNumber = x.location_whatsapp ?? string.Empty,
Logo = x.location_logo ?? string.Empty,
Id = x.Id,
}).ToList().ToList();
}
else
{
if (!string.IsNullOrWhiteSpace(searchTerm) && searchArea == 0)
{
locations = unitOfWork.Locations.Find(x => x.Visibility
|| x.location_name.Contains(searchTerm)
|| x.location_address.Contains(searchTerm)
|| x.location_general_area.Contains(searchTerm))
.OrderBy(x => x.Order)
.ToList();
}
if (string.IsNullOrWhiteSpace(searchTerm) && searchArea != 0)
{
locations = unitOfWork.Locations.Find(x => x.Visibility && x.location_area == searchArea).OrderBy(x => x.Order).ToList();
}
if (!string.IsNullOrWhiteSpace(searchTerm) && searchArea != 0)
{
locations = unitOfWork.Locations.Find(x => x.Visibility && x.location_area == searchArea
|| x.location_name.Contains(searchTerm)
|| x.location_address.Contains(searchTerm)
|| x.location_general_area.Contains(searchTerm))
.OrderBy(x => x.Order)
.ToList();
}
locationsVM = locations
.Select(x => new LocationVM()
{
ActivityHours = x.location_open_time ?? string.Empty,
ContactName = x.location_contact_name ?? string.Empty,
FirstPHone = x.first_phone_number ?? string.Empty,
SecondPHone = x.second_phone_number ?? string.Empty,
IsRefrigirated = x.location_refrigerated_medication,
LocationAdress = x.location_address ?? string.Empty,
LocationAreaName = x.location_general_area ?? string.Empty,
WhatsappNumber = x.location_whatsapp ?? string.Empty,
Logo = x.location_logo ?? string.Empty,
Id = x.Id,
}).ToList()
.ToList();
}

Add Autocomplete Address

Add Autocomplete Address
I have a problem with the code.
No results found
I'm doing a job application form.
Controller
public JsonResult Getprovinces()
{
List<mydistrict> provincel = new List<mydistrict>();
provincel = (from p in _auc.mytable
select p).ToList();
return Json(provincel);
}
public JsonResult Getamphoes(int province_code)
{
List<mydistrict> amphoelist = new List<mydistrict>();
amphoelist = (from Provinces in _auc.mytable
where Provinces.province_code == province_code
select Provinces).ToList();
return Json(amphoelist);
}
public JsonResult Getdistrict(int province_code, string amphoe_code)
{
List<mydistrict> districtslist = new List<mydistrict>();
districtslist = (from district in _auc.mytable
where district.province_code == province_code
where district.amphoe_code == amphoe_code
select district).ToList();
return Json(districtslist);
}
public JsonResult detail(int province_code, string amphoe_code,string district_code)
{
List<mydistrict> detail = new List<mydistrict>();
detail = (from de in _auc.mytable
where de.province_code == province_code
where de.amphoe_code == amphoe_code
where de.district_code == district_code
select de).ToList();
return Json(detail);
}
view
<select id="mydistrict_province" onchange="showAmphoes()" class="form-control">
<option value=""></option>
</select><br />
<select id="mydistrict_amphoe" onchange="showDistricts()" class="form-control">
<option value=""></option>
</select><br />
<select id="mydistrict_district" onchange="showZipcode()" class="form-control">
<option value=""></option>
</select><br />
<input id="mydistrict_zipcode" class="form-control" />
script
$(document).ready(function () {
showProvinces();
});
function showProvinces() {
var url = '#Url.Content("~/")' + "Employee/Getprovinces";
var callback = function (result) {
$("#mydistrict_province").empty();
for (var i = 0; i < result.length; i++) {
$("#mydistrict_province").append(
$('<option></option>')
.attr("value", "" + result[i].province_code)
.html("" + result[i].province)
);
}
showAmphoes();
};
ajax(url, callback);
}
function showAmphoes() {
var province_code = $("#mydistrict_province").val();
var url = '#Url.Content("~/")' + "Employee/Getamphoes";
var callback = function (result) {
console.log(result);
$("#mydistrict_amphoe").empty();
for (var i = 0; i < result.length; i++) {
$("#mydistrict_amphoe").append(
$('<option></option>')
.attr("value", "" + result[i].amphoe_code)
.html("" + result[i].amphoe)
);
}
showDistricts();
};
ajax(url, callback);
}
function showDistricts() {
var province_code = $("#mydistrict_province").val();
var amphoe_code = $("#mydistrict_amphoe").val();
var url = '#Url.Content("~/")' + "Employee/Getdistrict";
var callback = function (result) {
$("#mydistrict_district").empty();
for (var i = 0; i < result.length; i++) {
$("#mydistrict_district").append(
$('<option></option>')
.attr("value", "" + result[i].district_code)
.html("" + result[i].district)
);
}
showZipcode();
};
ajax(url, callback);
}
function showZipcode() {
var province_code = $("#mydistrict_province").val();
var amphoe_code = $("#mydistrict_amphoe").val();
var district_code = $("#mydistrict_district").val();
var url = '#Url.Content("~/")' + "Employee/Getdetail";
var callback = function (result) {
for (var i = 0; i < result.length; i++) {
$("#mydistrict_zipcode").val(result[i].zipcode);
}
};
ajax(url, callback);
}
function ajax(url, callback) {
$.ajax({
"url": url,
"type": "GET",
"dataType": "json",
})
.done(callback);
}
Result
enter image description here
Help me please, Thanks
Your problem is that you don't send any parameter to your method so you can use below code to send parameter for showAmphoes:
var url = '#Url.Action("Getamphoes","Employee")' + '/?province_code=' + province_code;
and for showDistricts:
var url = '#Url.Action("Getdistrict", "Employee")' + '/?province_code=' + province_code + '&amphoe_code=' + amphoe_code;

Recover id in display list using combobox

i need to recover the id of element selected in combobox in dev express
and this is the code of combobox:
#Html.DevExpress().ComboBox(
settings =>
{
settings.Name = "comboBox4";
settings.Width = 180;
settings.SelectedIndex = 0;
settings.Properties.DropDownWidth = 550;
settings.Properties.DropDownStyle = DropDownStyle.DropDownList;
settings.CallbackRouteValues = new { Controller = "Editors", Action = "MultiColumnComboBoxPartial" };
settings.Properties.CallbackPageSize = 30;
settings.Properties.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;
settings.Properties.TextFormatString = "{1}";
settings.Properties.ValueField = "Id";
settings.Properties.ValueType = typeof(string);
settings.Properties.Columns.Add("Id", "Id", 130).SetColVisible(false);
// settings.Properties.Columns.Add("Id", "Id", 130).SetColVisibleIndex(1);
settings.Properties.Columns.Add("Nom", "Nom", 130);
settings.Properties.Columns.Add("Prenom", "Prenom", Unit.Percentage(100));
settings.Properties.Columns.Add("DateNaissance", "DateNaissance", 60);
settings.Properties.Columns.Add("CodeClient", "CodeClient", 100);
}
).BindList(client).GetHtml()
and this the method ajax how i put the value of any custom with ajax:
function Addprojet() {
debugger;
var nom = $("#nom2_I").val();
var description = $("#Description_I").val();
var client = $("#comboBox4_I").val();
var chef = $("#chefid_I").val();
var complexite = $("#comboBox1_I").val();
var taille = $("#comboBox2_I").val();
var datedebut = $("#datedebut_I").val();
$.ajax({
url: "/Projet/AjouterProjet?nom=" + nom + "&description=" + description + "&client=" + client + "&chef=" + chef + "&complexite=" + complexite + "&taille=" + taille + "&datedebut=" + datedebut, // /Controlleur/Action
type: "POST",
dataType: 'text',
//data : {Nom: nom},
success: function (responseText) {
debugger;
if (responseText == "True") {
location.replace("/Client/listeclients");
}
else {
alert("error");
}
}
});
}
</script>
how can i resolve this issue because i need to recover the id of client without displaying in the list in the combobox
can semeone help me to fix it .

Asp.net mvc 5 C# how to loop through model list?

Here in my code, I am getting the day of the week into my model object than i parse it into Json but i would like to know if
is there a way to make this more simplier and more Effective?
Thanks for your answers!
public JsonResult GetCalendarByParam(int year, string month, int date, string type, string operation)
{
DateWeekModels returnDate = new DateWeekModels();
returnDate.Week = new List<Day>();
Day dy1 = new Day();
Day dy2 = new Day();
Day dy3 = new Day();
Day dy4 = new Day();
Day dy5 = new Day();
Day dy6 = new Day();
Day dy7 = new Day();
var monthReceive = DateTime.ParseExact(month, "MMMM", CultureInfo.CurrentCulture).Month;
var dt = new DateTime(year, monthReceive, date);
switch (type)
{
case "Month":
if (operation == "+")
{
dt = dt.AddMonths(1);
}
else
{
dt = dt.AddMonths(-1);
if (DateTime.Compare(dt, DateTime.Now) < 0)
{
dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
}
}
break;
case "Week":
if (operation == "+")
{
dt = dt.AddDays(7);
}
else
{
dt = dt.AddDays(-7);
if (DateTime.Compare(dt, DateTime.Now) < 0)
{
dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
}
}
break;
}
dt.ToString("ddd", new System.Globalization.CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.Name));
returnDate.Year = dt.Year;
returnDate.Month = dt.ToString("MMMM", new System.Globalization.CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.Name));
dy1.dayName = dt.ToString("ddd", new System.Globalization.CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.Name));
dy1.dayNumber = dt.Day;
dt = dt.AddDays(1);
dy2.dayName = dt.ToString("ddd", new System.Globalization.CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.Name));
dy2.dayNumber = dt.Day;
dt = dt.AddDays(1);
dy3.dayName = dt.ToString("ddd", new System.Globalization.CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.Name));
dy3.dayNumber = dt.Day;
dt = dt.AddDays(1);
dy4.dayName = dt.ToString("ddd", new System.Globalization.CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.Name));
dy4.dayNumber = dt.Day;
dt = dt.AddDays(1);
dy5.dayName = dt.ToString("ddd", new System.Globalization.CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.Name));
dy5.dayNumber = dt.Day;
dt = dt.AddDays(1);
dy6.dayName = dt.ToString("ddd", new System.Globalization.CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.Name));
dy6.dayNumber = dt.Day;
dt = dt.AddDays(1);
dy7.dayName = dt.ToString("ddd", new System.Globalization.CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.Name));
dy7.dayNumber = dt.Day;
returnDate.Week.Add(dy1);
returnDate.Week.Add(dy2);
returnDate.Week.Add(dy3);
returnDate.Week.Add(dy4);
returnDate.Week.Add(dy5);
returnDate.Week.Add(dy6);
returnDate.Week.Add(dy7);
return Json(returnDate, JsonRequestBehavior.AllowGet);
}
then with jquery I send my object to my id but i have to hardcode it too is there a way to pass my id to my object so i don't have to hardcode but simply loop it ? thank you!
<script>
var previousMonth = document.getElementById("previousMonth");
previousMonth.addEventListener("click", function () { calendarManager("Month", "-") }, false);
var nextMonth = document.getElementById("nextMonth");
nextMonth.addEventListener("click", function () { calendarManager("Month", "+") }, false);
var nextWeek = document.getElementById("nextWeek");
nextWeek.addEventListener("click", function () { calendarManager("Week", "+") }, false);
var previousWeek = document.getElementById("previousWeek");
previousWeek.addEventListener("click", function () { calendarManager("Week", "-") }, false);
function calendarManager(type, operator) {
var monthNow = $("#month").html();
var yearNow = $("#year").html();
var dayNow = $("#date1").html();
$.ajax({
type: "POST",
url: '#Url.Action("GetCalendarByParam", "Home")',
dataType: "Json",
data: {
"year": yearNow,
"month": monthNow,
"date": dayNow,
"type": type,
"operation": operator
},
success: function (data) {
$(".month").html(data.Month);
$(".year").html(data.Year);
var id;
for (var i = 1, n = 0; i < 8;i++,n++){
$("Day" i).html(data.Week[n].dayName);
//$("#date1").html(data.Week[0].dayNumber);
//$("#day2").html(data.Week[1].dayName);
//$("#date2").html(data.Week[1].dayNumber);
//$("#day3").html(data.Week[2].dayName);
//$("#date3").html(data.Week[2].dayNumber);
//$("#day4").html(data.Week[3].dayName);
//$("#date4").html(data.Week[3].dayNumber);
//$("#day5").html(data.Week[4].dayName);
//$("#date5").html(data.Week[4].dayNumber);
//$("#day6").html(data.Week[5].dayName);
//$("#date6").html(data.Week[5].dayNumber);
//$("#day7").html(data.Week[6].dayName);
//$("#date7").html(data.Week[6].dayNumber);
}
$(".tbDay1").attr("data-title", data.Week[0].dayName + " " + data.Week[0].dayNumber);
$(".tbDay2").attr("data-title", data.Week[1].dayName + " " + data.Week[1].dayNumber);
$(".tbDay3").attr("data-title", data.Week[2].dayName + " " + data.Week[2].dayNumber);
$(".tbDay4").attr("data-title", data.Week[3].dayName + " " + data.Week[3].dayNumber);
$(".tbDay5").attr("data-title", data.Week[4].dayName + " " + data.Week[4].dayNumber);
$(".tbDay6").attr("data-title", data.Week[5].dayName + " " + data.Week[5].dayNumber);
$(".tbDay7").attr("data-title", data.Week[6].dayName + " " + data.Week[6].dayNumber);
},
});
};
UPDATE
I was able to reduce my jquery code to this
<script>
var previousMonth = document.getElementById("previousMonth");
previousMonth.addEventListener("click", function () { calendarManager("Month", "-") }, false);
var nextMonth = document.getElementById("nextMonth");
nextMonth.addEventListener("click", function () { calendarManager("Month", "+") }, false);
var nextWeek = document.getElementById("nextWeek");
nextWeek.addEventListener("click", function () { calendarManager("Week", "+") }, false);
var previousWeek = document.getElementById("previousWeek");
previousWeek.addEventListener("click", function () { calendarManager("Week", "-") }, false);
function calendarManager(type, operator) {
var monthNow = $("#month").html();
var yearNow = $("#year").html();
var dayNow = $("#date1").html();
$.ajax({
type: "POST",
url: '#Url.Action("GetCalendarByParam", "Home")',
dataType: "Json",
data: {
"year": yearNow,
"month": monthNow,
"date": dayNow,
"type": type,
"operation": operator
},
success: function (data) {
$(".month").html(data.Month);
$(".year").html(data.Year);
var idDate, idDay,classTbDay;
for (var i = 1, n = 0; i < 8; i++, n++) {
idDate = "#date" + i;
idDay = "#day" + i;
classTbDay = ".tbDay" + i;
console.log(idDate);
$(idDate).html(data.Week[n].dayNumber);
$(idDay).html(data.Week[n].dayName);
$(classTbDay).attr("data-title", data.Week[n].dayName + " " + data.Week[n].dayNumber);
}
},
});
};
Using loops, your c# code should reduce like this:
public JsonResult GetCalendarByParam(int year, string month, int date, string type, string operation)
{
DateWeekModels returnDate = new DateWeekModels();
returnDate.Week = new List<Day>();
for (int i=0; i<7; i++) {
returnDate.Week.Add(new Day());
}
var monthReceive = DateTime.ParseExact(month, "MMMM", CultureInfo.CurrentCulture).Month;
var dt = new DateTime(year, monthReceive, date);
switch (type)
{
case "Month":
if (operation == "+")
{
dt = dt.AddMonths(1);
}
else
{
dt = dt.AddMonths(-1);
if (DateTime.Compare(dt, DateTime.Now) < 0)
{
dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
}
}
break;
case "Week":
if (operation == "+")
{
dt = dt.AddDays(7);
}
else
{
dt = dt.AddDays(-7);
if (DateTime.Compare(dt, DateTime.Now) < 0)
{
dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
}
}
break;
}
dt.ToString("ddd", new System.Globalization.CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.Name));
returnDate.Year = dt.Year;
returnDate.Month = dt.ToString("MMMM", new System.Globalization.CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.Name));
foreach (Day thisDay in returnDate.Week) {
thisDay.dayName = dt.ToString("ddd", new System.Globalization.CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.Name));
thisDay.dayNumber = dt.Day;
dt = dt.AddDays(1);
}
return Json(returnDate, JsonRequestBehavior.AllowGet);
}

How to send array from jquery to webmethod in C#

I'd like to pass an array to a c# webmethod but don't have a good example to follow. Thanks for any assistance.
Here is what I have so far:
My array:
function ReadAllGridviewData() {
var ArrayUph = new Array();
GVUPHLineItems = document.getElementById("GVUPHLineItems");
for (var i = 1; i < GVUPHLineItems.rows.length; i++) {
var txtQty = GVUPHLineItems.rows[i].cells[1].getElementsByTagName('input');
var txtStyle = GVUPHLineItems.rows[i].cells[2].getElementsByTagName('input');
var spanstyleDesc = GVUPHLineItems.rows[i].cells[3].getElementsByTagName('span');
var txtPackage = GVUPHLineItems.rows[i].cells[4].getElementsByTagName('input');
var txtPrice = GVUPHLineItems.rows[i].cells[7].getElementsByTagName('input');
if (txtStyle[0].value != '' && txtQty[0].value !='') {
var ArryUph = new Array();
ArryUph['LineNumber'] = i;
ArryUph['Quantity'] = txtQty[0].value;
ArryUph['Style'] = txtStyle[0].value;
ArryUph['StyleDescription'] = spanstyleDesc[0].innerHTML;
ArryUph['Package'] = txtPackage[0].value;
ArryUph['SelectFlag'] = 'N';
ArryUph['Price'] = 0.0;
var ArryStyle = new Array();
for (var j = 0; j < 6; j++) {
var spanStyle = GVUPHLineItems.rows[i].cells[5].childNodes[1].childNodes[1].childNodes[1].childNodes[j].cells[0].innerText;
var inputCoverId = GVUPHLineItems.rows[i].cells[5].childNodes[1].childNodes[1].childNodes[1].childNodes[j].cells[1].getElementsByTagName('input');
var inputColorID = GVUPHLineItems.rows[i].cells[5].childNodes[1].childNodes[1].childNodes[1].childNodes[j].cells[2].getElementsByTagName('input');
if (inputCoverId[0].value != '' && inputColorID[0].value != '') {
var tempArryStyle = new Array();
tempArryStyle['CoverPosition'] = spanStyle;
tempArryStyle['CoverID'] = inputCoverId[0].value;
tempArryStyle['ColorID'] = inputColorID[0].value;
ArryStyle.push(tempArryStyle);
}
}
var ArryOptions = new Array();
for (var k = 0; k < 6; k++) {
var inputOpt = GVUPHLineItems.rows[i].cells[6].childNodes[1].childNodes[1].childNodes[1].childNodes[k].cells[0].getElementsByTagName('input');
if (inputOpt[0].value != '') {
var tempArryOptions = new Array();
tempArryOptions['Opt'] = inputOpt[0].value;
ArryOptions.push(tempArryOptions);
}
}
ArryUph['StyleCovers'] = ArryStyle;
ArryUph['Options'] = ArryOptions;
ArrayUph.push(ArryUph);
}
}
Here is my Jquery call:
$.ajax({ type: "POST",
url: "OrderEntry.aspx/ValidateUph",
data: JSON.stringify({ ArrayUph: ArrayUph }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var validstyle = data.d;
}
});

Categories

Resources