C# Web method is not calling in javascript - javascript

i create a web method and now i'm calling this in my java script file but it give an path error,it is not able to find path what i'm giving ..
Web method code is :
[System.Web.Services.WebMethod]
public static int ItemCount(string itemId)
{
int val = 0;
Item itm = Sitecore.Context.Database.GetItem(itemId);
val = itm.Children.Count;
return val;
}
java script function calling like as:
function GetItemCount(itemId) {
var funRes = "";
debugger;
try {
if (itemId != null) {
jQuery.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Views/GetItem.aspx/ItemCount",
data: { itemId: itemId },
dataType: "json",
async: false,
success: function (data) {
funRes = data.result;
},
error: function(err) {
alert(err.responseText);
}
});
}
} catch (ex) {
alert(ex.message);
}
return funRes;}
while i'm giving exact path for the C# method class but it's not working give an error on console, can anyone suggest me what i'm missing here..

There are few rules for ajax to work with asp.net.
Your WebMethod should be public and static.
If your WebMethod expects some parameter(s) than these parameter(s) must be passed as data in ajax.
Name of parameter(s) should be same in WebMethod and in data part of ajax.
Data passed from ajax should be in json string.For this you can use JSON.stringify or you will have to surround the values of parameter(s) in quotes.
Please check the below sample ajax call
function CallAjax()
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/CallAjax",
data: JSON.stringify({ name: "Mairaj", value: "12" }),
dataType: "json",
async: false,
success: function (data) {
//your code
},
error: function (err) {
alert(err.responseText);
}
});
}
[WebMethod]
public static List<string> CallAjax(string name,int value)
{
List<string> list = new List<string>();
try
{
list.Add("Mairaj");
list.Add("Ahmad");
list.Add("Minhas");
}
catch (Exception ex)
{
}
return list;
}
EDIT
If you use GET in ajax than you need to enable your webmethod to be called from GET request. Add [System.Web.Script.Services.ScriptMethod(UseHttpGet = true)] on top of WebMetod
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
public static int ItemCount()

Just Modify the javascript function as below
function GetItemCount(itemId) {
var funRes = "";
debugger;
try {
if (itemId != null) {
jQuery.ajax({
type: "GET",
url: "/Views/GetItem.aspx",
data: 'itemID=' + itemId,
contentType: "application/html",
dataType: "html",
success: function (response) {
funRes= response.result;
}
});
}
} catch (ex) {
alert(ex.message);
}
return funRes;
}

I am not sure it is a solution for every question subject which web method not fire. But I discovered today when there is ' char in the string. Web Method not firing.

Related

Can not send data from c#(controller) to javascript

I have this code on my JavaScript file:
temp="string";
var myJson = JSON.stringify(temp);
$.ajax(
{
url: '/MemoryGame/updateStatus',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: myJson,
success: function (response) {
alert("success");
if (response == 'Okay') {
checkStatus(temp.myID);
}
else {
ConnectionChanged();
}
},
error: function (errorThrown) {
console.log(errorThrown);
ConnectionChanged();
}
});
And this controller:
[HttpPost]
public string updateStatus(string updatedJson)
{
var Player = JsonConvert.DeserializeObject<GameDataClass>(updatedJson);
var Opponent = JsonConvert.DeserializeObject<GameDataClass>(System.IO.File.ReadAllText(System.IO.Path.Combine(_env.WebRootPath, Player.OpponentID + ".json")));
... }
I tried to change $.ajax to $.post method, also changed
public string updateStatus
to
public JsonResult updatedStatus
But neither of this didn't work. myJson on javascript contain data but when it reaches controller updatedJson is empty. I've never had this kind of experience so I'm using this code from another project and it works very well there. So can somebody suggest me what I'm doing wrong?
temp="string";
// (0)
var myJson = JSON.stringify(temp);
$.ajax(
{
url: '/MemoryGame/updateStatus?updatedJson=' + temp, // (1)
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '', // (2)
success: function (response) {
alert("success");
if (response == 'Okay') {
checkStatus(response.myID);
}
else {
ConnectionChanged();
}
},
error: function (errorThrown) {
ConnectionChanged();
}
});
Or if this does not have to be passed as a parameter, then do the following:
(0) var formData = new FormData(); formData.append('updatedJson', temp);
(1) url: '/MemoryGame/updateStatus',
(2) data: formData,
$.ajax is a fonction from the jQuery library, does your project include it ?
You can also check the Javascript console of your browser to see if it contains errors. On Firefox and Chrome you can access it by pressing F12.

The GET request call returns wrong result

I would like to call my WEB API in .NET Core from the jQuery like below:
[HttpGet("GetText")]
public async Task<IActionResult> GetText()
{
try
{
string welCome = "Test";
JsonSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
return Json(welCome, JsonSettings);
}
catch(Exception ex)
{
throw ex;
}
}
And the jQuery caller:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'GET',
url: "http://localhost:5000/api/mycontroller/GetText?callback=?",
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
if (data.success) {
alert('Success -> ' + JSON.stringify(data.statusText));
}
},
error: function (data) {
alert('Error -> ' + JSON.stringify(data.statusText));
}
});
});
</script>
The API is calling successfully but it seems it will then redirect to error function in my Ajax and show the error alert with a "success" as it's statusText. I mean this: Error -> "Success" I am not sure why this happens?
I would like to print welCome as a success result and in the alert command.
Also please note that I am calling this API from another project, I mean the jQuery's AJAX code is inside another project. I am not sure if it is important or not at all.
The jQuery's AJAX Caller path: file:///C:/Users/Me/Desktop/Path/index.html
The API's address: C:\Users\Me\Documents\Visual Studio 2017\Projects\ThisProject\MyAPI
And the URL of this API: url: "http://localhost:5000/api/mycontroller/GetText",
Try the C# Code in the following manner :
[HttpGet("GetText")]
public async Task<IActionResult> GetText()
{
try
{
string welCome = "Test";
return Ok(new { message = welCome });
}
catch(Exception ex)
{
throw ex;
}
}
Try the Jquery Code in the following manner :
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'GET',
url: 'http://localhost:5000/api/mycontroller/GetText',
success: function (response) {
alert('Success' + response.message);
},
failure: function (response) {
}
});

How to read boolean value from json via JS

I want read returned value from this method:
public ActionResult ClientIsBlocked(int? clientId)
{
if (!clientId.HasValue)
return Json(null);
bool isBlocked = false;
try
{
isBlocked = this.clientsProvider.GetClientById(clientId.Value).IsBlocked;
}
catch
{
// logg
}
return Json(isBlocked);
}
in java script in my view. It should be async/ajax. How to do that?
It is my js code in view.
function isBlocked(id) {
$.ajax({
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "GET",
url: '#Url.Action("ClientIsBlocked", "CustomerManagement", new { Area = "CustomerManagement" })',
data: JSON.stringify({ 'clientId': id }),
success: function(data) {
if(!data.success) {
}
}
})
In your action change :
return Json(isBlocked);
to:
return Json(isBlocked,JsonRequestBehavior.AllowGet);
otherwise your ajax may fail throwing exception:
Server Error in '/' Application.
This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.
and in js in success callback:
success: function(data) {
alert(data); // data is the bool that is returned by action
}

Calling a controller method via javascript

I have an ASP.NET application where I am invoking a controller methode from JavaScript. My JavaScript code looks like this:
function OnNodeClick(s, e) {
$.ajax({
type: "POST",
url: '#Url.Action("DeviceManifests", "Home")',
data: { selectedRepo: e.node.name },
success: function (data) {
if (data != null) {
$('#GridView').html(data);
}
},
error: function (e) {
alert(e.responseText);
}
});
}
This calls the Home controller's DeviceManifests() method.
This is what the method looks like:
public ActionResult DeviceManifests(Guid selectedRepo)
{
var repoItem = mock.GetRepoItem(selectedRepo);
return View("Delete", repoItem.childs);
}
The method gets invoked but the problem is the Delete-View doesn't get rendered. There's no error, just nothing happens.
How can I update my code to get my desired behaviour?
Do like below code so if you have error you will have it in alert box or success result will rendered in DOM
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("DeviceManifests", "Home")',
data: { selectedRepo: e.node.name },
dataType: "html",
success: function (data) {
if (data != null) {
$('#someElement').html(data);
}
}
},
error: function (e) {
alert(e.responseText);
}
});
You can do the redirect in the javascript side.
function OnNodeClick(s, e) {
$.ajax({
type: "GET ",
url: '#Url.Action("DeviceManifests", "Home")',
data: { selectedRepo: e.node.name },
success: function (msg)
{
window.location = msg.newLoc;
}
});
}
Make sure you include the redirect url in action and return JsonResult and not ActionResult. I'd also include pass the guid so that the destination Action and let it look up the data.

Do you need to use two calls - 1 get and 1 post in ajax or can you send data back with the success / failure?

I have the following controller method:
public JsonResult CreateGroup(String GroupName)
{
ApplicationUser user;
var userName = User.Identity.Name;
using (DAL.GDContext context = new DAL.GDContext())
{
user = context.Users.FirstOrDefault(u => u.UserName == userName);
if (user != null)
{
var group = new Group();
group.GroupName = GroupName;
group.Members.Add(user);
context.Groups.Add(group);
context.SaveChanges();
}
}
string result = userName;
return Json(result, JsonRequestBehavior.AllowGet);
}
with the following ajax call:
$(function () {
$('#CreateGroup').on("click", function () {
var groupName = $('#groupname').val();
if (groupName != '') {
$.ajax({
url: '#Url.Action("CreateGroup","AjaxMethods")',
type: "POST",
data: JSON.stringify({ 'GroupName': groupName }),
dataType: "json",
cache: false,
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("success");
CreateGroup(data);
},
error: function () {
alert("An error has occured!!!");
}
});
}
});
The CreateGroup function fails saying "Uncaught ReferenceError: data is not defined"
Do i have to use another Json request - type post - to get the username?
you can do the call without using JSON.stringify. Also your controller method has a cache attribute that may yield more control. Personally, I would use the controller cache control. You are probably getting a cached version of the controller call prior to returning data.
[OutputCache(NoStore = true, Duration = 0)]
public ActionResult CreateGroup(string GroupName)
$.ajax({
url: '#Url.Action("CreateGroup","AjaxMethods")',
type: "POST",
data: { 'GroupName': groupName },
dataType: "json",
traditional: true,
success: function (data, status, xhr ) {
alert("success");
CreateGroup(data);
},
error: function () {
alert("An error has occured!!!");
}
});
NOTE: Update success callback.

Categories