I have a IEnumerable Collection of Custom DataType that I'm sending to the Client.
I want to parse the collection in my JQuery method. Currently I'm getting value as "undefined". Below is my code:
Service:
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
IEnumerable<CustomData> GetSetting(long userId);
public IEnumerable<CustomData> GetSetting(long userId)
{
var tempData = Context.DialogSettings.Where(item => item.id == userId).ToList();
return tempData.Select(dialogSetting => new CustomData { KeyName = dialogSetting.KeyName, KeyValue = dialogSetting.KeyValue }).ToList();
}
[DataContract]
public class CustomData
{
[DataMember]
public String KeyName;
[DataMember]
public String KeyValue;
}
Client:
function LoadSetting() {
$.ajax({
type: "GET",
url: "SampleService.svc/GetSetting",
data: '{"userId": "' + 1 + '"}',
processData: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var myHistoryList = data.d;
alert(myHistoryList); // here I'm getting value: undefined
},
error: function (result) {
alert('Service call failed: ' + result.status + '' + result.statusText);
}
});
}
});
From the comments on the question I can safely presume that the following js code will work:
if(typeof data != 'undefined'){
alert(data[0].KeyName); //this will yield a value.
}
else
alert('Ok. This is weird');
Related
I am getting table records, I need to send it to Controller so that I can send email. When I tried with following code, it's throwing error
var emailList = '';
$('.checkBoxClass').each(function () {
if ($(this).is(':checked')) {
emailList += $(this).val() + ',';
}
});
body = 'Hi Team'
console.log('emIl ' + emailList);
var baseUrl = ".";
$.ajax({
type: "GET",
url: baseUrl + "/Dashboard/GetFinanceSendMail",
data: "{'emailList': '" + JSON.stringify(emailList) + "', body' : '" + body + "' }",
success: function (json) {
alert(json);
}
});
Error as : HTTP Error 404.15 - Not Found The request filtering module
is configured to deny a request where the query string is too long.
Most likely causes: Request filtering is configured on the Web server
to deny the request because the query string is too long.
I have tried to add following code, still same error
var formData = new FormData();
var objArr = [];
objArr.push({ "emIl": emailList, });
//JSON obj
formData.append('objArr', JSON.stringify(objArr))
body = 'Hi Team'
console.log('emIl ' + emailList);
var baseUrl = ".";
$.ajax({
type: "POST",
url: baseUrl + "/Dashboard/GetFinanceSendMail",
processData: false,
contentType: false,
data: formData,
Here is Controller Code
[HttpGet]
public JsonResult GetFinanceSendMail(string emailList, string body)
{
List<string> emails = emailList.Split(',').ToList();
// Send Email add optiona arg to the method
_openPobl.TriggerFinanceEmail(body, emails);
return Json(emails, JsonRequestBehavior.AllowGet);
}
fix the action, remove [get]
Route[("~/Dashboard/GetFinanceSendMail")]
public JsonResult GetFinanceSendMail(string emailList, string body)
and ajax
var emailList = '';
$('.checkBoxClass').each(function () {
if ($(this).is(':checked')) {
emailList += $(this).val() + ',';
}
});
var body = 'Hi Team';
$.ajax({
type: "POST",
url: "/Dashboard/GetFinanceSendMail",
data: {emailList: emailList, body : body },
success: function (json) {
alert(json);
}
});
but if you want to use post much more reliable to create a viewmodel class
public class ViewModel
{
public string EmailList {get;set;}
public string Body {get;set;}
}
action
Route[("~/Dashboard/GetFinanceSendMail")]
public JsonResult GetFinanceSendMail(ViewModel model)
.....
and ajax
$.ajax({
type: "POST",
url: "/Dashboard/GetFinanceSendMail",
data: { model: {emailList: emailList, body : body } },
success: function (json) {
alert(json);
}
});
currently i keep getting the alert request failed whenever i try to pass back data from view to controller.
leafletLats and leafletLngs are an array, but im not sure of the datatype. They are derived from coord which is of type LatLng[].
may i know what is causing the Post method to not pass through? is it the problems in the controller?
in View
routeControl.on('routeselected', function (e) {
var coord = e.route.coordinates;
var name = e.route.name;
var leafletLats = coord.map(function(point) {
return [point.lat];
});
var leafletLngs = coord.map(function(point) {
return [point.lng];
});
alert('Array size = ' + coord.length + '\nCoordinates: \n' + leafletLats);
alert('Array size = ' + coord.length + '\nCoordinates: \n' + leafletLngs);
//alert('Array size = ' + coord.length + '\nCoordinates: \n' + coord.join('\n'));
$.ajax({
type: 'Post',
url: '/Map/GetRouteCoordinates',
data: JSON.stringify(leafletLats),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(`Request passed!`);
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(`Request failed!`);
}
});
in controller
[HttpPost]
public ActionResult GetRouteCoordinates(MyModel test)
{
//do something with the result
Debug.WriteLine("data passed back");
return View();
}
public class MyModel
{
public List<MyModel_Value> latList { get; set; }
}
public class MyModel_Value
{
public double lat { get; set; }
}
did some modification and changing the data to data: JSON.stringify({ arr: stringifiedArr }) works for me
I am trying to send the variables from the GetTelephoneFunction to the AJAX query so it can reach the controller, but what I have tried does not work. Please help and thank you.
jQuery:
$.ajax({
type: "POST",
url: "/Status/GetUrlSource",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "url": $("#urlInput").val(), "user": $("#user").val(), "pass":$("#pass").val(),"freq": $("#freqInput").val() }),
dataType: "html",
success: function (result, status, xhr) {
//Code
}
function GetUrlTelePhone(html, status, result) {
var geturlUser = url.split('?username=')[1].split('&password')[0];
var geturlPass = url.split("&password=")[1];
var getUrlMain = url.split("?")[0];
var geturlParameters = url.split("aspx")[1];
}
Controller
public string GetUrlSource(string url, string freq, string user, string pass)
{
//user = user.Substring(0, 10) != "?" ? "?" + user : user;
//pass = pass.Substring(0,20) != "&" ? "&" + pass : pass;
url = url.Substring(0, 4) != "http" ? "http://" + url : url;
string htmlCode = "";
using (WebClient client = new WebClient())
{
try
{
htmlCode = client.DownloadString(url);
}
catch (Exception)
{
return "Not Found";
}
}
//SqlConnect(url);
Hangfire(url,freq,user,pass);
return htmlCode;
}
am using .netcore 1.1 , Visual studio 2017 , Jquery version = "3.2.1"
,am trying to make the MVC controller to get data from my page ,
i have 2 arrays in java , one is an array of Object (model view) and one is an array of strings
objects array always return error 400 (bad request)
2- string array ,always send null to the controller
i followed the below answers with no success
https://stackoverflow.com/a/13255459/6741585
and
https://stackoverflow.com/a/18808033/6741585
below is my chtml page
//#region send data back t oserver
$('#Savebtn').click(function () {
console.log(editedRows);
var UpdatedRows = JSON.stringify({ 'acActivityed': editedRows });
console.log(UpdatedRows);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/acActivity/Edit",
//traditional: true,
data: UpdatedRows ,
dataType: "json",
success: function (data) {
// here comes your response after calling the server
alert('Suceeded');
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error : " + jqXHR.responseText);
}
});
});
//#endregion
//#region deleted all selected
$('#DeleteSelectedbtn').on('click', function () {
if (confirm("Are you sure to delete All Selected ?????")) {
var selectedData = [];
var selectedIndexes;
selectedIndexes = grid.getSelectedRows();
jQuery.each(selectedIndexes, function (index, value) {
selectedData.push(grid.getDataItem(value).id);
});
console.log(selectedData);
var SelectedIds = selectedData.join(',') ;
console.log(SelectedIds);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/acActivity/DeleteSelected",
data: JSON.stringify({ "ids": SelectedIds }),
dataType: "json",
success: function (data) {
grid.render();
},
error: function (err) {
alert("error : " + err);
}
});
}
});
//#endregion
and both do have data as below console shots
the selected ID's one
my Controller
this one should expect the list of object and always return bad request ,
[HttpPost]
[ValidateAntiForgeryToken]
//public jsonResult Edit( List<acActivitytbl> acActivityed)
public ActionResult Edit( List<acActivitytbl> acActivityed)
{
foreach (acActivitytbl it in acActivityed)
{
logger.Log(LogLevel.Info, it.ID);
logger.Log(LogLevel.Info, it.Name);
logger.Log(LogLevel.Info, it.IsActive);
}
//return View(acActivityed);
return Json(new { success = true, responseText = "end of Page" });
}
that one should expect the delimited string ,but always receive null
public ActionResult DeleteSelected(string ids)
{
try
{
char[] delimiterChars = { ' ', ',', '.', ':', ' ' };
string[] words = ids.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
if (words != null && words.Length > 0)
{
foreach (var id in words)
{
bool done = true; //new acActivitiesVM().Delete(Convert.ToInt32(id));
logger.Log(LogLevel.Info, " acActivities ID {0} is Deleted Scussefully ", id);
}
return Json(new { success = true, responseText = "Deleted Scussefully" });
}
return Json(new { success = false, responseText = "Nothing Selected" });
}
catch (Exception dex)
{
..... removed to save space
});
}
}
i know there is something missing here ,but i cannot find it ,any help in that ??
I try to Save data in Db using EF6 through Web service , but it runs forever without any indicators to error .
My web method :
[System.Web.Script.Services.ScriptService]
public class FamilyRelationService : System.Web.Services.WebService
{
[WebMethod]
public int Update(int id, string name)
{
int result = -1;
try
{
using (HRCTX ctx = new HRCTX())
{
using (FamilyRelationRepository familyRelationRepo = new FamilyRelationRepository(ctx))
{
FAMILYRELATION family = familyRelationRepo.Find(id);
family.RELATION_NAME = name;
family.State = StateInterface.State.Modified;
familyRelationRepo.InsertOrUpdate(family);
result = ctx.Save();
}
}
}
catch (Exception ee)
{
throw;
}
return result;
}
}
My Calling function :
function Update(e) {
name = $("#txt_relation_name").val();
id = $("#lbl_relation_code").text();
$.ajax({
type: "POST",
url: "FamilyRelationService.asmx/Update",
data: "{'id':'" + id + "', 'name':'" + name + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var result = response.d;
if (result > 0) {
$("#name", row).text(name);
row.removeClass("highlightRow");
CloseEditStudentDialog();
}
else {
alert('Error...');
}
},
failure: function (msg) {
alert(msg);
}
});
return false;
}
<input type="submit" id="btn_save" value="Save" onclick="Update(); return false;" />
In FireBug Console :
I see the following :