I have the below ajax call code from jquery.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: oAxn.ds,
data: JSON.stringify(oAxn.p(graphsDrpDwn)),
beforeSend: function () {
$(".errorMsg").hide();
YC.toggleLoadingImg(tabId, false);
},
success: function (graphData) {
if (typeof oAxn.s === "function") {
if (graphData.reportData.ErrorMsg !== "Success") {
$(".errorMsg").show().html(graphData.reportData.ErrorMsg);
$("#tabs").hide();
YC.toggleLoadingImg(tabId, true);
} else {
//Inorder to avoid flicker, we hide in style sheet on page load.
$("#tabs").show();
$(".lblDrp").show();
$("#MainDiv").show();
YC.showRangeSel();
YC.toggleLoadingImg(tabId, true);
oAxn.s(graphData, grphOneID, grphTwoID);
}
}
},
error: function (err) {
YC.toggleLoadingImg(tabId, true);
}
});
The method that gets the parameters JSON.stringify(oAxn.p(graphsDrpDwn)) is:
getDealerParams: function (graphsDrpDwn) {
/// <summary>We gather the parameters required for dealer tab</summary>
/// <param name="graphsDrpDwn" type="string">Holds the dropdown list id</param>
return {
//We get these from hidden inputs, since they won't be available
// in the query string for framed in reports
shopId: $(".txtShopId").val(),
siteId: $("." + graphsDrpDwn).find(":selected").attr("data-field"),
dealerId: $("." + graphsDrpDwn).find(":selected").val(),
frmDate: $(".tsFrom").val(),
toDate: $(".tsTo").val()
};
},
All parameters are getting values except frmDate, toDate.
I can see the values in client side but when passed to controller two are always null.
And it is only happening in my system, it is working fine in my colleagues machine.
can some body advise what could be wrong here?
This is not the ideal solution but it worked for us on couple projects. In Global.asax we put the following code:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
var newCulture = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
newCulture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
newCulture.DateTimeFormat.DateSeparator = "/";
Thread.CurrentThread.CurrentCulture = newCulture;
}
Of course you need to change the date format to the one you need.
Adding the below attributes in aspx file for page directive worked for me.
UICulture="es" Culture="es-US"
Related
Can't make friends out of my AJAX and MVC 6 controller.
This is how I define AJAX call for SetFormValues POST-action:
Index.cshtml
$.ajax({
type: "Post",
url: "Home/SetFormValues",
data: { Name: name, Phone: phone },
dataType: "json",
success: function (result) {
SuccessFunction(result)
},
error: function () {
alert("ALARM!");
},
async: false
})
I see that the controller works and executes SetFormValues action which is defined as the following:
HomeController.cs
[HttpPost]
public JsonResult SetFormValues(string Name, string Phone)
{
string NameErrorStr = string.IsNullOrWhiteSpace(Name) ? "Обязательное поле" : string.Empty;
string PhoneErrorStr = string.IsNullOrWhiteSpace(Phone) ? "Обязательное поле" : string.Empty;
var result = new { NameError = NameErrorStr, PhoneError = PhoneErrorStr };
var jresult = Json(result);
return jresult;
}
Debugger shows that action executes and my resulting JSON object fills correctly:
Finally, his is how SuccessFunction(result) is defined:
Index.cshtml again
function SuccessFunction(result) {
alert("Success function shit executed. result=" +
result + "NameError=" +
result.NameError + ". PhoneError=" +
result.PhoneError);
$("#nameerror").append(result.NameError);
$("#phoneerror").append(result.PhoneError);
}
Function works, alert is raised but result stay 'undefined' no matter what I do:
result = [object Object]
result.val = undefined
Maybe I have to deserialize JSON result properly or fill some properties in it's declaration above, I don't know.
I'm using the lattest libraries for jquery, validate and unobtrusive.
I also tried JSON.parse(result), as it mentioned in the lattest jQuery specification, but it didn't work as well.
Please, help me :)
In asp.net core, by default, the serializer uses camelCase property names for json serialization. So your result will be like this
{"nameError":"some message","phoneError":"some message here"}
Javascript is case sensitive. So use the correct case
$("#nameerror").append(result.nameError);
$("#phoneerror").append(result.phoneError);
For reference : MVC now serializes JSON with camel case names by default
its working perfectly when i have added this line in startup file
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
services.AddDbContext<DataContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DbCrudOperation")));
}
function Edit(id) {
$.ajax({
type: 'GET',
url: "/AjacCrud/EditPahe/" + id,
dataType: 'JSON',
contentType: "application/json",
success: function (response) {
$("#nameEmp").val(response.ID);
console.log(response.ID);
},
error: function (GetError) {
alert(GetError.responseText);
}
});
};
I have been trying to load return a JsonResults action from a controller in MVC using ajax call. I can see that the alert() function is triggering well but the ajax is not executing. I have search for several sources but to no avail.
public JsonResult FillBusinessLicenceL3(int? selectedID)
{
var bl3_Items = db.LevelThreeItems.Where(l3 => l3.LevelTwoItem_ID == selectedID);
return Json(bl3_Items, JsonRequestBehavior.AllowGet);
}
The below too is the javascript calling for the json method.
<script>
function FillBussLicence_L3items() {
alert("You have clicked me");
var bl2_Id = $('#BussLicenceL2_ID').val();
//alert(document.getElementById("BussLicenceL2_ID").value);
alert(bl2_Id);
$.ajax({
url: 'StartSurvey/FillBusinessLicenceL3/' + bl2_Id,
type: "GET",
dataType: "JSON",
data: "{}", // { selectedID : bl2_Id },
//contentType: 'application/json; charset=utf-8',
success: function (bussLicence_L3items) {
$("#BussLicenceL3_ID").html(""); // clear before appending new list
$.each(bussLicence_L3items, function (i, licenceL3) {
$("#BussLicenceL3_ID").append(
$('<option></option>').val(licenceL3.LevelThreeItem_ID).html(licenceL3.LevelThreeItem_Name));
});
}
});
}
Also, I have tried this one too but no execution notice.
Thanks a lot for your help in advance.
After looking through the browser's console, I noticed that the LINQ query was tracking the database and was creating a circular reference so I changed the query to the following and voila!!
public JsonResult FillBusinessLicenceL3(int? selectedID)
{
var bl3_Items = db.LevelThreeItems.
Where(k => k.LevelTwoItem_ID == selectedID).
Select(s => new { LevelThreeItem_ID = s.LevelThreeItem_ID, LevelThreeItem_Name = s.LevelThreeItem_Name });
return Json(bl3_Items, JsonRequestBehavior.AllowGet);
}
There was nothing wrong with the ajax call to the controller.
I have a click function that grabs rows from an grid. The return value is a list of objects which represent each row. I use JSON.stringify so I can send the data to my SaveJobs action on my Home Controller. The following properties work and my controller action recognizes the data, but it is not in valid JSON format.
contentType: 'application/json; charset=utf-8'
data: { data: JSON.stringify(editedRows) }
However, I found through research that the below method is preferred since it is a valid JSON format, but my data variable on my controller action is null (returning no data to perform my action on) and I could not debug the issue. Why does the action variable not recognize this? Thank you.
$('#SaveJobs').on('click', function () {
editedRows = getEditedRows();
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: savePlannedJobsUrl,
cache: false,
data: JSON.stringify({ data: editedRows }),
dataType: "text",
success: function (result) {
if (result === 'Success') {
alert('The records you have edited are saved');
}
else {
alert('There was an error with the server. All records may not have been saved.');
}
$("*").css("cursor", "");
},
error: function (HtmlHttpRequest, ajaxOptions, thrownError) {
var htmlObj = $.parseHTML(HtmlHttpRequest.responseText);
var savedJson = JSON.stringify(editedRows);
if (htmlObj !== null) {
var htmlBody = htmlObj[htmlObj.length-1].outerText;;
}
tryToWriteError(htmlBody, savedJson);
}
});
return false;
});
Controller
[HttpPost]
public string SaveJobs(string data)
{
// CODE HERE
}
ANSWER:
I marked #Queti's answer, and more specific to my problem see the link in my comment that will help for MVC projects. That resolution will skip creating DTOs.
The issue is that you are sending in an array of objects, but your action method is expecting a string.
It appears that your getEditedRows method is returning an array of objects.
I recommend you create a model on the server that matches what you are passing in. Something like:
public class MyDto
{
int id { get; set; }
string comments { get; set; }
}
And then update your method signature to accept that as the parameter:
public string SaveJobs(List<MyDto> data)
Below an Ajax call wrapped inside a jQuery autocomplete source function. checking the return value in Fiddler and also in Chrome's Network console, I can see that the data is being returned to the view and in the correct format.
However, the normal list of items that occur when the user starts typing do not appear. You can type as fast/slow for as little/long as you want and nothing will appear.
I've set a breakpoint in the controller method (this is an ASP MVC site) just to make sure that part of the program was functioning properly, and it fires every time.
I'm only a few weeks new to jQuery so any help would be greatly appreciated. Thanks!
$(function () {
$('#DRMCompanyId').autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("compSearch", "AgentTransmission")',
type: 'GET',
dataType: 'json',
data: request,
success: function (data) {
alert(data);
response($.map(function (value, key) {
alert(value);
return {
label: value,
value: key
};
}));
}
});
},
minLength: 1
});
});
EDIT
I added a couple alerts to the code. The alert(data) will fire but the alert(value) will not.
Here is a copy of the returned json from the Chrome's debugging console
And here is the controller method that returns the key/value pair in the form of a Dictionary object.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
nsmgr.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices");
Dictionary<string, string> companies = new Dictionary<string, string>();
foreach (XmlNode childNode in parentNode)
{
if (!String.IsNullOrWhiteSpace(childNode["content"].InnerText))
{
try
{
string name = childNode["title"].InnerText;
string id = childNode["content"].InnerText.Substring(0, 6);
companies.Add(id, name);
}
catch (Exception ex)
{
}
}
}
return Json(companies, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
results = ex.InnerException.ToString();
}
return Json(results, JsonRequestBehavior.AllowGet);
The $.map function expects an array/object to enumerate on, as first argument. ref jQuery.map.
try changing
$.map(function (value, key) {
to
$.map(data, function (value, key) {
Regards.
The jQuery documentation: http://api.jquery.com/jQuery.map/ says that the $.map function expects two parameters; the first being an array. I think that you need to use the $.each method instead.
I also believe that in this context, response is a callback function that you are supposed to invoke with the data from AJAX as the parameter, as in response(data).
Shooting from the hip here, I think that your success handler should look about like this:
success: function (data) {
var x, array = [];
for(x in data) {
array.push({
label: data[x].value,
value: data[x].key
};
}
response(data);
}
I am using revealing module pattern and knockout to bind a form. When data is entered in that form(registration), it needs to be posted back to MVC4 web method.
Here is the Jquery code
/*
Requires JQuery
Requires Knockout
*/
op.TestCall = function () {
// Private Area
var _tmpl = { load: "Loading", form: "RegisterForm"};
var
title = ko.observable(null)
template = ko.observable(_tmpl.load),
msg = ko.observable(),
postData = ko.observable(),
PostRegistration = function () {
console.log("Ajax Call Start");
var test = GetPostData();
$.ajax({
type: "POST",
url: obj.postURL, //Your URL here api/registration
data: GetPostData(),
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8'
}).done(Success).fail(Failure);
console.log("Ajax Call End");
},
GetPostData = function () {
var postData = JSON.stringify({
dummyText1: dummyText1(),
dummyText2: dummyText2(),
});
return postData;
}
return {
// Public Area
title: title,
template: template,
dummyText1: dummyText1,
dummyText2: dummyText2
};
}();
The controller code is simple as per now
// POST api/registration
public void Post(string data)
{
///TODO
}
When i am trying to, capture the data (using simple console.log) and validate it in jslint.com, it's a valid Json.
I tried hardcoding the data as
data: "{data: '{\'name\':\'niall\'}'}",
But still i get as null, in my web method.
Added the tag [System.Web.Script.Services.ScriptMethod(UseHttpGet = false, ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)] to my Post method in controlled, but still no fruitful result
Even tried JSON.Stringify data: JSON.stringify(data) but still i get null in my web-method.
I am not able to figure out the solution.
Similar issue was found # this link
http://forums.asp.net/t/1555940.aspx/1
even Passing parameter to WebMethod with jQuery Ajax
but didn't help me :(
MVC and WebApi uses the concept of Model Binding.
So the easiest solution is that you need to create a Model class which matches the structure of the sent Json data to accept the data on the server:
public void Post(MyModel model)
{
///TODO
}
public class MyModel
{
public string DummyText1 { get; set; }
public string DummyText1 { get; set; }
}
Note: The json and C# property names should match.
Only escaped double-quote characters are allowed, not single-quotes, so you just have to replace single quotes with double quotes:
data: "{data: '{\"name\":\"niall\"}'}"
Or if you want to use the stringify function you can use it this way:
data: "{data: '" + JSON.stringify(data) + "'}"