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;
}
});
Related
this is my jQuery code on submit button
function SubmitFilter()
{
var transactionNumb = $("#transactionNumber").val();
var cardHolderName = $("#cardHolder").val();
$.ajax({
type: "GET",
url: "https://localhost:7197/Transactions?transaction_number="+transactionNumb+"&cardholder="+cardHolderName,
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data)
{
alert(data);
}
});
}
And this the code behind class from here I'm not able to call the GetTransactions method directly..ajax method goes to onget method only.
Here my intention is to get the jarray value in ajax success function
you can look full code if you need in this link
https://technotesfromwork.blogspot.com/2022/07/tech-note.html
please let me know how i can change this code to return the jarray value to ajax. thanks in advance..
public void OnGet(int CurrentPage,int transaction_number, string cardholder)
{
this.Authorize = HttpContext.Session.GetString("Roles");
this.CurrentPage = CurrentPage;
if(CurrentPage==0)
{
this.CurrentPage = 1;
}
ViewData["Title"] = "Transactions List";
Transactions = GetTransactions(this.CurrentPage,transaction_number,cardholder);
}
public JArray GetTransactions(int currentPage,int transaction_number , string cardholder)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", HttpContext.Session.GetString("JwtToken"));
var url = $"{BaseApiUrl}/transactions?page={currentPage}&limit={PageSize}";
var filters ="";
var requestUri = new Uri(url);
var responseTask = client.GetAsync(requestUri);
responseTask.Wait();
var result = responseTask.Result;
// this.TotalResults = result.Headers.GetValues("X-Paging-Pages");
this.TotalResults = "5";
if (result.IsSuccessStatusCode)
{
var reportResults = Task.Run(async() => await result.Content.ReadAsAsync<JArray>()).Result;
return reportResults;
}
}
return JArray.Parse("[]");
}
Create a handler to retrieve a JSON result for the ajax call :
public void OnGetAsJson(int CurrentPage,int transaction_number, string cardholder)
{
this.Authorize = HttpContext.Session.GetString("Roles");
this.CurrentPage = CurrentPage;
if(CurrentPage==0)
{
this.CurrentPage = 1;
}
ViewData["Title"] = "Transactions List";
var transactions = GetTransactions(this.CurrentPage,transaction_number,cardholder);
return new JsonResult(transactions);
}
and change the ajax url to this :
function SubmitFilter()
{
var transactionNumb = $("#transactionNumber").val();
var cardHolderName = $("#cardHolder").val();
$.ajax({
type: "GET",
url: "https://localhost:7197/Transactions?handler=AsJson?transaction_number="+transactionNumb+"&cardholder="+cardHolderName,
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data)
{
alert(data);
}
});
}
I am using the Google.DataTable wrapper by #zoranmax. I can get a single line chart to work fine. What I want to do is display multiple lines.
When I return the JSON to AJAX call to create the chart I am told that I have no columns in the table.
The C# return produces a list of string that is indexed, so for each series, there is a 0,1,2 etc.
Here is an example of the JSON output JSON Output, there are 20 of these arrays that are returned from the C# code in one hit to AJAX call.
As you can see the JSON validates, but it just won't work.
The AJAX call:
$.ajax({
url: 'ProjectCharts/GetMultiChartData',
datatype: 'json',
type: 'get',
async: false,
data: { section: section, uid: uid, from: from, to: to },
contentType: 'application/json; charset=utf-8',
success: function (d) {
parsedData = $.parseJSON(d);
console.log(parsedData);
var data = new google.visualization.DataTable(parsedData);
var chart = new google.visualization.LineChart(document.getElementById('chart'));
var options = multiLineChartOptions();
chart.draw(data, options);
},
error: function () {
alert("Error");
}
});
The C# part:
public string CreateJsonMultiChartDataTable(string serial, string guid, string datefrom, string dateto)
{
var serials = _context.LogTagRawData.Where(x => x.ProjectGuid == guid).Select(x => x.SerialNumber).Distinct().ToList();
var projectUid = guid;
var from = datefrom;
var to = dateto;
List<string> multiDt = new List<string>();
try
{
foreach (var s in serials)
{
var data = GetChartDataFromSqlServer(s, projectUid, from, to);
var dt = new Google.DataTable.Net.Wrapper.DataTable();
dt.AddColumn(new Google.DataTable.Net.Wrapper.Column(Google.DataTable.Net.Wrapper.ColumnType.Datetime, "Date", "Date"));
dt.AddColumn(new Google.DataTable.Net.Wrapper.Column(Google.DataTable.Net.Wrapper.ColumnType.Number, "Data", "Data"));
foreach (var item in data)
{
Google.DataTable.Net.Wrapper.Row r = dt.NewRow();
r.AddCellRange(new Google.DataTable.Net.Wrapper.Cell[]
{
new Google.DataTable.Net.Wrapper.Cell(Convert.ToDateTime(item.ReadingDate)),
new Google.DataTable.Net.Wrapper.Cell(item.ReadingValue)
});
dt.AddRow(r);
}
multiDt.Add(dt.GetJson());
}
}
catch (Exception ex)
{
var m = ex.Message;
}
var sb = new StringBuilder();
sb.Append("[");
foreach(var i in multiDt)
{
sb.Append("[");
sb.Append(i);
sb.Append("],");
}
sb.Append("]");
string xx = sb.ToString();
int yy = xx.LastIndexOf(',');
xx = xx.Remove(yy, 1);
return xx;
}
JSON call from AJAX
public JsonResult GetMultiChartData(string serial, string uid, string from, string to)
{
var dateFrom = Convert.ToDateTime(from).ToString("yyyy-MM-dd HH:mm:ss");
var dateTo = Convert.ToDateTime(to).AddMinutes(1).ToString("yyyy-MM-dd HH:mm:ss");
var g = new GetChartData(_context, _configuration);
var items = g.CreateJsonMultiChartDataTable(serial, uid, dateFrom, dateTo);
var deserialisedJsonData = JsonConvert.DeserializeObject(items);
return Json(JsonConvert.SerializeObject(deserialisedJsonData, Formatting.Indented));
}
I try to save a file (image) on C# MVC and JS with the following function js
function Add() {
var data = new FormData();
var files = $("#txtUploadFile").get(0).files;
var cod = document.getElementById('cod').value;
var mat = document.getElementById('mat').value;
var status = document.getElementById('status').value;
var plant = document.getElementById('plant').value;
if (files.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < files.length; x++) {
data.append("file" + x, files[x]);
data.append("mat", mat);
data.append("status", status);
data.append("plant", plant);
data.append("code", cod);
}
$.ajax({
type: 'POST',
url: '/Pred/Admin/AddPred',
contentType: false,
processData: false,
data: data,
success: function (response) {
if(response.msg == 1)
{
refreshTable(response.data);
}
alert('Predio agregado.');
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
}
});
}
}
}
and on the codebehind I used it
public ActionResult AddPred()
{
int isInsert=0;
string route = ConfigurationManager.AppSettings["MAPS_ROUTE"];
string[] status, plants, mats, codes;
int stat;
try
{
var requeststatus = Request.Params;
status = requeststatus.GetValues("status");
plants = requeststatus.GetValues("plant");
codes = requeststatus.GetValues("cod");
mats = requeststatus.GetValues("mat");
if (status[0] == "On")
stat= 1;
else
stat= 0;
string plant = plants[0];
string mat = mats[0];
string code = codes[0];
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent != null && fileContent.ContentLength > 0)
{
var fileName = fileContent.FileName;
var path = Path.Combine(Server.MapPath(route), fileName);
path = Server.MapPath(route) + fileName;
var sqlpath = "." + route + "/" + fileName;
fileContent.SaveAs(path);
isInsert = ma.InsertPred(code, mat, stat, plant, sqlpath);
}
}
merge.preds = ma.GetPreds();
return Json(new { success = true, data = merge.preds, msg = isInsert }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("add failed");
}
}
But the server response ever is
POST myserver/Preds/Admin/AddPred 500 (Internal Server Error)
and I used console.log but I can't to get the error information, When used this code on local side, it's runs Okey, save the image and return model for refresh the front, but when put the aplication on the server, only return error, others funtions works (modal show, return model with json) but doesn't work save a image, I set permissions (write, load, modify) on the server folder,
someone give a idea for solves this problem, I don't know whats wrong
Try like this :
function getCities(id) {
$.ajax({
type: "POST",
url: "#Url.Action("Index", "Default")",
data: '{id: id }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
//alert(response.responseData);
window.location = '/Default/YourView';//
},
error: function (response) {
alert("error!"); //
}
});
}
//In your controller
public JsonResult Index(string id)
{
merge.country= mp.Country();
merge.city= mp.City(id);
return Json("you can return an object or a string, what you want");
}
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 .
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);
}