jquery -ajax not check the boolean value from controller - javascript

i have a controller action which is return a boolean result to the jquery.
[HttpGet]
public ActionResult IsVoucherValid(string voucherCode)
{
bool result = false;
var voucher = new VoucherCode(voucherCode);
if(voucher.Status==0)
{
result = true;
}
return Json(result);
}
and call this controller using ajax code
$.ajax({
url: '/Account/IsVoucherValid?voucherCode=' + code,
type: 'Get',
contentType: 'application/json;',
success: function (data) {
alert("success");
if (data) {
//if result=true, want to work this
$("#person-data").css({ "display": "block" });
}
},
error:alert("error")
});
in the success of ajax the json result is true then want to work the css. but this is not working please help me.

result is a variable name that only exists in that action method. It will not be included in the JSON.
I'm pretty sure that your boolean value will be stored in data since you are only sending back a single value:
$.ajax({
url: '/Account/IsVoucherValid?voucherCode=' + code,
type: 'Get',
contentType: 'application/json;',
success: function (data) {
if (data) { //if result=true, want to work this
$("#person-data").css({ "display": "block" });
}
}
});
If in doubt, do console.log(data) to see what it contains. You should at least be doing minimal debugging before you bring the question to us.
Also, as #Stephen Muecke points out below, if you are retrieving this data with GET, you need to use:
return Json(result, JsonRequestBehavior.AllowGet);

Related

HTTP 303 redirect from XHR long poll does not redirect [duplicate]

I use $.ajax() to poll an action method every 5 seconds as follows:
$.ajax({
type: 'GET', url: '/MyController/IsReady/1',
dataType: 'json', success: function (xhr_data) {
if (xhr_data.active == 'pending') {
setTimeout(function () { ajaxRequest(); }, 5000);
}
}
});
and the ActionResult action:
public ActionResult IsReady(int id)
{
if(true)
{
return RedirectToAction("AnotherAction");
}
return Json("pending");
}
I had to change the action return type to ActionResult in order to use RedirectToAction (originally it was JsonResult and I was returning Json(new { active = 'active' };), but it looks to have trouble redirecting and rendering the new View from within the $.ajax() success callback. I need to redirect to "AnotherAction" from within this polling ajax postback. Firebug's response is the View from "AnotherAction", but it's not rendering.
You need to consume the result of your ajax request and use that to run javascript to manually update window.location yourself. For example, something like:
// Your ajax callback:
function(result) {
if (result.redirectUrl != null) {
window.location = result.redirectUrl;
}
}
Where "result" is the argument passed to you by jQuery's ajax method after completion of the ajax request. (And to generate the URL itself, use UrlHelper.GenerateUrl, which is an MVC helper that creates URLs based off of actions/controllers/etc.)
I know this is a super old article but after scouring the web this was still the top answer on Google, and I ended up using a different solution. If you want to use a pure RedirectToAction this works as well. The RedirectToAction response contains the complete markup for the view.
C#:
return RedirectToAction("Action", "Controller", new { myRouteValue = foo});
JS:
$.ajax({
type: "POST",
url: "./PostController/PostAction",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (result) {
if (result.responseText) {
$('body').html(result.responseText);
}
}
});
C# worked well
I just changed the JS because responseText was not working for me:
$.ajax({
type: "POST",
url: posturl,
contentType: false,
processData: false,
async: false,
data: requestjson,
success: function(result) {
if (result) {
$('body').html(result);
}
},
error: function (xhr, status, p3, p4){
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
console.log(err);
}
});
You could use the Html.RenderAction helper in a View:
public ActionResult IsReady(int id)
{
if(true)
{
ViewBag.Action = "AnotherAction";
return PartialView("_AjaxRedirect");
}
return Json("pending");
}
And in the "_AjaxRedirect" partial view:
#{
string action = ViewBag.ActionName;
Html.RenderAction(action);
}
Reference:
https://stackoverflow.com/a/49137153/150342

Table not refreshing after post function in JQuery and ASP.NET CORE

I have made a filtering method. This method is working like a charm and when I type something the table updates to the search string. This is my method for the search:
loadList() {
var searchString = $(".search-input").val();
$.post('/Translation/List?searchString=' + searchString, function (data) {
$(".table-content-view").html(data);
});
}
And when I wanna insert a new record I call this method:
saveTranslation() {
$.ajax({
url: '/Translation/Edit',
data: new FormData($(`${tr.selectedclass} #translation-form`)[0]),
processData: false,
contentType: false,
type: 'POST',
success: function (response) {
if (response.success === true) {
loadList();
}
}
});
}
This method works fine (confirmed with postman and chrome dev tools). The problem is I need to press F5 to see the new record instead that it refresh instantly. As you can see I call the method LoadList() to refresh the table but this doesn't work.
NOTE:
I use a partial view for the table.
This is my C# method for the list:
[HttpPost]
public async Task<IActionResult> List(string searchString)
{
var translations = _context.translation.AsQueryable();
translations = translations.OrderBy(x => x.CORETRANSLATIONID);
if (!String.IsNullOrEmpty(searchString))
{
translations = translations.Where(x => x.ORIGINAL.Contains(searchString));
}
return PartialView(await translations.ToListAsync());
}
Can someone point me in the right direction?
In my post method in JQuery I changed it too
saveTranslation() {
$.ajax({
url: '/Translation/Edit',
data: new FormData($(`${tr.selectedclass} #translation-form`)[0]),
processData: false,
contentType: false,
type: 'POST',
success: function (response) {
loadList();
}
});
}
The if statement was not necessary.

passing an array of int to MVC controller using ajax javascript

What am I doing wrong here?
I can successfully pass 4 bool params to a controller. Now I want to pass an array of int to my controller but it doesn't work - I've left my working code in the example(commented out) so you can see I'm not changing that much - I think I'm missing something simple (it is 17:44 afterall!!!). I can see the array is populated using the alert(rolesChecked); statement:
var rolesChecked = [];
$('[type="checkbox"].role-checkbox').each(function () {
if (this.checked)
{
rolesChecked.push($(this).val());
}
});
alert(rolesChecked);
//var administrator = $('#cbAdministrator').is(":checked");
//var manager = $('#cbManager').is(":checked");
//var technician = $('#cbTechnician').is(":checked");
//var transcriber = $('#cbTranscriber').is(":checked");
if (rolesChecked.count > 0){//administrator || manager || technician || transcriber) {
$.ajax({
url: '#Url.Action("GetFutureHolidays", "Employee")',
type: 'GET',
dataType: 'json',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: {
roleIdXXXs: rolesChecked
//includeAdministrator: administrator,
//includeManager: manager,
//includeTechnician: technician,
//includeTranscriber: transcriber
},
success: function (data) {
//do something...
}
});
}
Controller Action:
public string GetFutureHolidays(List<int> roleIdXXXs)//bool includeAdministrator, bool includeManager, bool includeTechnician, bool includeTranscriber)
{
//do something
}
with the old code, the controller action would be hit... with the array, it never gets hit... What am I missing here...
also, I think List<int> roleIdXXXs should be fine, but I also tried List<string>, int[] and string[] in case it isn't!!!
You need to add the traditional: true ajax option to post back an array to the collection
$.ajax({
url: '#Url.Action("GetFutureHolidays", "Employee")',
type: 'GET',
dataType: 'json',
cache: false,
data: { roleIdXXXs: rolesChecked },
traditional: true, // add this
success: function (data) {
}
});
Refer also the answer to this question for more detail on what the options does and the form data it generates.
In your if statement, instead of rolesChecked.count, use rolesChecked.length
You can't submit a list like this from Ajax, the quickest fix in the process you are using is to use serialization-desalinization process, you can send it as
roleIdXXXs: JSON.stringify(rolesChecked)
on Action:
public ActionResult GetFutureHolidays(string rolesChecked)
{
var test = new JavaScriptSerializer().Deserialize<List<int>>(rolesChecked);
}
You should use JSON.stringify() on you AJAX call lice this:
data: {
roleIdXXXs: JSON.stringify(rolesChecked)
//includeAdministrator: administrator,
//includeManager: manager,
//includeTechnician: technician,
//includeTranscriber: transcriber
}

Form post warning message after upgrading jquery

I have upgraded to jquery 1.10.2. I am using jquery migrate and I am having the warning message "jQuery.parseJSON requires a valid JSON string"
I have not understood how I can correct that. Can anyone help me out with the best solution of how I can remove the warning message
The javascript is as follows:
function Search() {
$.ajax({
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "html",
url: "#Url.Action("Search")",
data: JSON.stringify({myModel: $("#DateFrom").val()}),
success: function (data)
{
$("#NewDiv").html(data);
},
error: function (request, status, error)
{
DisplayError(ParseErrorFromResponse(request.responseText, "Unknown error"), true);
}
});
}
In the Controller:
public PartialViewResult Search(myModel myModel)
{
return PartialView("SearchResult", myModel);
}
ParseErrorFromResponse:
Function ParseErrorFromResponse(responseText, defaultError)
{
var text = responseText.replace("<title>", "TitleStart");
var startIndex = text.indexOf("TitleStart");
var endIndex = text.indexOf("TitleEnd");
return (startIndex == -1 || endIndex == -1) ? defaultError : text.substring(startIndex + 10, endIndex);
}
You need to send your data as JSON.
Where you have data: $("#DateFrom").val(), replace it with data: JSON.stringify({$("#DateFrom").val()}).
EDIT: You may need to send it as JSON.stringify({(myModel: $("#DateFrom").val()}).
The error may be related to "" or false values that used to convert to null in versions of jQuery prior to 1.9.0 per THIS PAGE
Here it the relevant excerpt including the suggested solution:
JQMIGRATE: jQuery.parseJSON requires a valid JSON string
Cause: Before jQuery 1.9.0, the $.parseJSON() method allowed some
invalid JSON strings and returned null as a result without throwing an
error. This put it at odds with the JSON.parse() method. The two
methods are aligned as of 1.9.0 and values such as an empty string are
properly not considered valid by $.parseJSON().
Solution: If you want to consider values such as "" or false
successful and treat them as null, check for them before calling
$.parseJSON(). Since falsy values such as an empty string were
previously returned as a null without complaint, this code will
suffice in most cases:
var json = $.parseJSON(jsonString || "null");
If your own code is not
calling $.parseJSON() directly, it is probably using AJAX to retrieve
a JSON value from a server that is returning an empty string in the
content body rather than a valid JSON response such as null or {}. If
it isn't possible to correct the invalid JSON in the server response,
you can retrieve the response as text:
$.ajax({
url: "...",
dataType: "text",
success: function( text ) {
var json = text? $.parseJSON(text) : null;
...
}
});
Remove content-type attribute and do like this:
function Search() {
$.ajax({
cache: false,
url: "#Url.Action("Search","ControllerName")",
dataType:"html",
data:
{
myModel: $("#DateFrom").val()
},
success: function (data)
{
$("#NewDiv").html(data);
},
error: function (request, status, error)
{
DisplayError(ParseErrorFromResponse(request.responseText, "Unknown error"), true);
}
});
}
and in action:
public PartialViewResult Search(string myModel)
{
return PartialView("SearchResult", myModel);
}
I think it's because you're missing double quotes around key myModel in line
...
data: JSON.stringify({myModel: $("#DateFrom").val()},
...
and not because of jquery version upgrade.try using
data: JSON.stringify({"myModel": $("#DateFrom").val()},
Try like this.. You have to return Json as result from your Search().
public JsonResult Search(myModel myModel)
{
return Json(result);
}
and also in you Script, try like this..
$.ajax({
type:"POST"
cache: false,
contentType: "application/json; charset=utf-8",
url: "#Url.Action("Search","ControllerName")",
dataType: "json",
data: JSON.stringify({"myModel": $("#DateFrom").val()}),
success: function (data)
{
$("#NewDiv").html(data);
}
});
Also check $("#DateFrom").val() is having correct value and put an
alert(data)
in success and check the returned data.
I have updated the url.

JSON pass null value to MVC 4 controller in IE9

I got some problem while posting JSON data into MVC 4 controller.
Below method is working fine in Firefox but unfortunately failed in IE 9
The JavaScript :
var newCustomer = {
CustName: $("#CustName").val(),
CustLocalName: $("#CustLocalName").val(),
CustNumber: $("#CustNumber").val(),
CountryID: $("#SelectCountry").val(),
City: $("#City").val()
};
$.ajax({
url: '#Url.Content("~/CustomerHeader/CreateCustomerHeader")',
cache: false,
type: "POST",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(newCustomer),
success: function (mydata) {
$("#message").html("Success");
},
error: function () {
$("#message").html("Save failed");
}
});
and this is my controller :
public JsonResult CreateCustomerHeader(CustomerHeader record)
{
try
{
if (!ModelState.IsValid)
{
return Json(new { Result = "ERROR", Message = "Form is not valid! Please correct it and try again." });
}
RepositoryHeader.Update(record);
return Json(new { Result = "OK", Record = record});
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
the "data" variable as in public JsonResult CreateCustomerHeader(CustomerHeader **data**) is getting NULL but while using FireFox it holds the correct value.
UPDATE : New method trying using $.post
function CreateNewCustomer(newCustomer) {
$.post("/CustomerHeader/CreateCustomerHeader",
newCustomer,
function (response, status, jqxhr) {
console.log(response.toString())
});
}
Based off the bit that you've shown, this is a simplified variation that may work more consistently, using jQuery.post() (http://api.jquery.com/jQuery.post/):
var data = {
CustName: $("#CustName").val(),
CustLocalName: $("#CustLocalName").val(),
CustNumber: $("#CustNumber").val(),
CountryID: $("#SelectCountry").val(),
City: $("#City").val()
};
$.post({
'#Url.Action("CreateCustomerHeader", "CustomerHeader")',
data,
function(response, status, jqxhr){
// do something with the response data
}).success(function () {
$("#message").html("Success");
}).error(function () {
$("#message").html("Save failed");
});
$.post() uses $.ajax as it's base, but abstracts some of the details away. For instance, $.post calls are not cached, so you don't need to set the cache state (and setting it is ignored if you do). Using a simple JavaScript object lets jQuery decide how to serialize the POST variables; when using this format, I rarely have issues with the model binder not being able to properly bind to my .NET classes.
response is whatever you send back from the controller; in your case, a JSON object. status is a simple text value like success or error, and jqxhr is a jQuery XMLHttpRequest object, which you could use to get some more information about the request, but I rarely find a need for it.
first of all I would like to apologize #Tieson.T for not providing details on JavaScript section of the view. The problem is actually caused by $('#addCustomerHeaderModal').modal('hide') that occurred just after ajax call.
The full script :
try{ ..
var newCustomer =
{
CustName: $("#CustName").val(),
CustLocalName: $("#CustLocalName").val(),
CustNumber: $("#CustNumber").val(),
CountryID: $("#SelectCountry").val(),
City: $("#City").val()
};
$.ajax({
url: '/CustomerHeader/CreateCustomerHeader',
cache: false,
type: "POST",
dataType: "json",
data: JSON.stringify(newCustomer),
contentType: "application/json; charset=utf-8",
success: function (mydata) {
$("#message").html("Success");
},
error: function () {
$("#message").html("Save failed");
}
});
}
catch(Error) {
console.log(Error.toString());
}
//$('#addCustomerHeaderModal').modal('hide')//THIS is the part that causing controller cannot retrieve the data but happened only with IE!
I have commented $('#addCustomerHeaderModal').modal('hide') and now the value received by controller is no more NULL with IE. Don't know why modal-hide event behave like this with IE9.
Thanks for all the efforts in solving my problem guys :-)

Categories