I trying call webmethod in my web project. I didnt found a problem in my codes and I called webmethod thousands of times before but I never see mistake like this before. Never enter my methods codes and it return my html page codes to me. ( sorry my bad english :)).. Please someone help me about that.
My Web method codes :
[WebMethod]
public static string GirisKontrol(string UserName, string Pass)
{
try
{
string strSonuc = "";
var context = new DBEntities();
var Kisi = context.users.Where(t => t.eposta== UserName && t.sifre == Pass).FirstOrDefault();
if (Kisi != null && Kisi.uye_onay==1)
{
HttpContext.Current.Session["UyeID"] = Kisi.ID;
HttpContext.Current.Session["Gorev"] = Kisi.gorev;
return Kisi.adsoyad;
}
else
return "0";
}
catch (Exception ex)
{
return "";
}
}
My javascript codes:
function GirisKontrol() {
PageMethods.GirisKontrol("asd", "sad", function(a) {
alert(a);
});
}
or I tried this but I got same result:
function test() {
$.ajax({
type: "POST",
url: "indexDeneme.aspx/GirisKontrol",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg);
}
});
}
This is result and it never go in c# codes:
enter image description here
Try this:
[WebMethod(EnableSession=true)]
Otherwise your method won't have access to the current SessionState, and the part where you try to save data to Session won't work.
The first example where you call PageMethods.GirisKontrol is unclear - your JavaScript isn't going to know about the server-side methods.
The second example using Ajax looks closer, but you're not passing any data.
data: "{}",
perhaps you mean this:
data: "{'UserName': 'asd', 'Pass': 'sad'}",
Related
I have a method in MVC that I post to it and I need to return some data back to process.
This is my MVC method that I post to and return Value is a json data.
[HttpPost]
public JsonResult GetCalculateAmortizationSchedule()
{
var data = ...
var httpClient = new HttpClient();
var response = httpClient.PostAsJsonAsync("http://localhost:62815/v1/APR/CalculateAmortizationSchedule", data).Result;
var returnValue = response.Content.ReadAsAsync<Dictionary<int, AmItem>>().Result;
return Json(returnValue);
}
This is my AJax call that successfully run the MVC method.
$('#MyForm').submit(function (e) {
debugger;
$.ajax({
url: "/home/GetCalculateAmortizationSchedule",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
alert("success");
},
error: function (result) {
alert("error");
}
});
e.preventDefault();
});
My problem is how to catch the return value from method? when I run this after return Json(returnValue) the value is not returning to Ajax method and instead of seeing the Success Alert I see the error Alert.
Try this:
success: function (result) {alert(JSON.stringify(result)); }
From the error you have posted in comments below, it appears Dictionary is not serializable. Try setting AllowGet as mentioned in other answers. If doesn't work, you will need to convert Dictionary to some other object that is serializable. Or you may follow this to serialize Dictionary to json in your controller.
How do I convert a dictionary to a JSON String in C#?
You should add JsonBehavious if you are not getting values.
return Json(returnValue, JsonRequestBehavior.AllowGet);
Try this piece of code :
return Json(returnValues, JsonRequestBehavior.AllowGet);
Yes, there are a whole bunch of posts with similar questions. I've tried to follow the answers in them, but my ajax call still isn't reaching the controller method.
controller (SalesController.cs):
[HttpGet]
public JsonResult fillVarietiesSelect(int species_id)
{
String[] alist = {"a","b","c"};
return Json(alist, JsonRequestBehavior.AllowGet);
}
javascript:
$('#species-select').on('change', function () {
var species_id = $('#species-select').val();
console.log("species id selected " + species_id);
alert("species id selected " + species_id);
$('#variety-select').empty();
$.ajax({
type: 'GET',
url: '#Url.Action("fillVarietiesSelect", "Sales")',
data: {species_id : species_id},
success: function (result) {
alert(result);
}
});
});
The on change event is firing, and the alert pops up with the correct data. I have a breakpoint set at the controller method, but execution doesn't seem to get there.
try doing exactly like following
Controller:
[HttpGet]
public ActionResult receive2(string p)
{
ViewBag.name = p;
List<string> lst = new List<string>() { p };
return Json(lst,JsonRequestBehavior.AllowGet);
}
Client side
$.ajax({
type: "GET",
url: "Main/receive2", // the method we are calling
contentType: "application/json; charset=utf-8",
data: { "p": $("#txtname").val() },
dataType:"json",
success: function (result) {
alert("yes");
alert('Yay! It worked!tim' + result);
window.location = "http://google.com";
// Or if you are returning something
},
error: function (result) {
alert('Oh no aa :(' + result[0]);
}
});
I have checked it's working
I had the same issue, changing the parameter from int to string resolved the problem.
On the server side I had,
public string RemoveByDocumentID(int DocumentID)
changing that to
public string RemoveByDocumentID(string DocumentID)
resolved the issue.
On the same context, I have another method in the same name (overloaded method). Which was also contributing to the issue, so I made the method name unique.
Your 404 error is telling you that #Url.Action is not being parsed by the view engine. The # is Razor syntax, so for this to work you need to be using a .cshtml extension for C# views or .vbhtml for VB views and be using MVC 3 or above.
I've been stuck at this error for a few days and still couldn't figure out what is wrong. Would be great if someone could just point me to the right direction of solving this issue.
Update:
I realise that error is gone when I commented "addMessages(xml)" in the updateMsg() function. How do I make it work then?
Error:
http://i.imgur.com/91HGTpl.png
Code:
$(document).ready(function () {
var msg = $("#msg");
var log = $("#log");
var timestamp = 0;
$("#name").focus();
$("#login").click(function() {
var name = $("#name").val();
if (!name) {
alert("Please enter a name!");
return false;
}
var username = new RegExp('^[0-9a-zA-Z]+$');
if (!username.test(name)){
alert("Invalid user name! \n Please do not use the following characters \n `~!##$^&*()=|{}':;',\\[\\].<>/?~##");
return false;
}
$.ajax({
url: 'login.php',
type: 'POST',
dataType: 'json',
data: {name: name},
success: function() {
$(".login").hide();
}
})
return false;
});
$("#form").submit(function() {
if (!msg.val()) {
return false;
}
$.ajax({
url: 'add_message.php',
type: 'POST',
dataType: 'json',
data: {message: msg.val()},
})
msg.val("");
return false
});
window.setInterval(function () {
updateMsg();
}, 300);
function updateMsg() {
$.post('server.php', {datasize: '1024'}, function(xml) {
addMessages(xml);
});
}
function addMessages(xml) {
var json = eval('('+xml+')');
$.each(json, function(i, v) {
tt = parseInt(v.time);
if (tt > timestamp) {
console.log(v.message);
appendLog($("<div/>").text('[' + v.username + ']' + v.message));
timestamp = tt
}
});
}
function appendLog(msg) {
var d = log[0]
var doScroll = d.scrollTop == d.scrollHeight - d.clientHeight;
msg.appendTo(log)
if (doScroll) {
d.scrollTop = d.scrollHeight - d.clientHeight;
}
}
});
It might help to read up on eval a bit. It looks like it doesn't do what you think it does.
eval() is a dangerous function, which executes the code it's passed with the privileges of the caller.
Also
There are safer (and faster!) alternatives to eval() for common use-cases.
It looks like what you're trying to do is get data from the server in the form of JSON. You'll need to make sure that your server returns something that is valid JSON, which you can verify here. Most server-side programming languages have a library that will turn an object into JSON to make that a piece of cake. Here's an example for php.
On the client-side, you'll need to change var json = eval('(' + xml + ')'); to var json = JSON.parse(xml); This will give you the javascript version of your php/perl/python/etc object. If it's an array, you can then iterate through it with a for loop, Array.prototype.forEach, or a variety of functions from different libraries, such as $.each or _.each.
SyntaxError: expected expression, got ')' usually cause by something like
exeFunction(a,b,)
See if your form submit function ajax causing such error
$("#form").submit(function() {
if (!msg.val()) {
return false;
}
$.ajax({
url: 'add_message.php',
type: 'POST',
dataType: 'json',
data: {message: msg.val()}, <-------
})
msg.val("");
return false
});
If you are triggering the java script on click or trigger any click. sometimes missing of 0 gives the above error.
delete
would JSON.stringify({datasize: '1024'}) do the trick? just a guess
When I ran below code for bttn click event it doesn't return a data for success method.
But it goes for controller method and return false (boolean value) as a out put.I need to pick that boolean value from javascript code.
Why it doesn't work ?
Javascript code is as below:
$('#btnClockInTime').off('click').on('click', function () {
var isClockOutTimeCompleted = true;
$.ajax({
url: "/Employees/IsClockOutTimeCompleted",
type: "GET",
dataType: "json",
cache: false,
data: { employeeId: employeeId },
success: function (data) {
if (!data) {
isClockOutTimeCompleted = data;
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
return false;
});
Controller Action Method is as below:
[HttpGet]
public JsonResult IsClockOutTimeCompleted(Guid employeeId)
{
var clockingDate = Convert.ToDateTime(DateTime.Today);
var isClockOutTimeCompleted = Repository.IsClockOutTimeCompleted(employeeId, clockingDate);
return Json(isClockOutTimeCompleted, JsonRequestBehavior.AllowGet);
}
Repository code is as below:
public bool IsClockOutTimeCompleted(Guid employeeId, DateTime clockingDate)
{
var clockOutTime = (from c in Catalog.EmployeeClockInOutTimes
where (c.Employee.Id == employeeId && c.Created == clockingDate && c.ClockOut == null)
select c).FirstOrDefault();
return clockOutTime == null;
}
UPDATE :
Response is as below :
UPDATE 2 :
Screen 1 :
Screen 2 :
Screen 3 :
As shown above images my debug doesn't come into success method.
After 2nd screen (when debug at error) it goes to controller and brings data.
3rd screen shows a status after returning from controller.Any idea ?
I would have thought that if you're return value is just false as a string then that will become your data value and as a result:
if (!data) { // won't fire }
As Darin says, if you wrap up your response Json inside an object and then use that to assign to your isClockOutTimeCompleted variable.
I wouldn't have thought you'd want to perform a boolean evaluation of your return value if it's a true/false return type, wouldn't you just want to assign it to isClockOutTimeCompleted either way?
if ur posting data to a controller method always use
'type':'POST' in ur ajax call &
change the [HTTPget] attribute from ur controller method to [httpPost]
below is my sample code which works fine
$.ajax({
url: 'Home/temp',
type: 'POST',
dataType: "json",
data: {'name':'surya'},
success: function (data) {
console.log(data);
//here i'm getting the data which i have passed
},
error: function () {
console.log("inside error")
}
});
and my controller code
[HttpPost]
public JsonResult temp(string name) {
return Json(name);
}
i'm getting back the data which i have passed in to the controller method via my jquery ajax..
may be u ought to change ur 'IsClockOutTimeCompleted' method where u are performing linq queries.just validate ur linq queries once..and also employeeId which ur passing into the controller is of type integer then instead of GUID as a parameter why dont u change the parameter type as int and see..
Regards
I'm a newbie in javascript, and I don't really understand the error I'm having.
I'm working on a MVC3 website, which has to monitor an embedded system.
Here is the javascript code that is running :
function GetTemp() {
var test = "gTe";
$.ajax({
url: '#Url.Action("../Carte/Get")',
type: 'GET',
data: {test: test},
success: function (result) {
if (result.charAt(4) == 'a') {
$("#LumAct").text(result.substr(0, 4) + " %");
alert('a');
}
...
And here is the c# action that returns a string
public String Get(String test)
{
flag = TCPClient.SendData(test);
if (flag == "1")
{
try
{
value = TCPClient.ReceiveData();
}
catch
{
value = "Erreur";
}
}
else value = "Erreur";
return value;
}
The error I have is in firebug, which tells me :
TypeError: result.charAt is not a function
[Stopper sur une erreur]
if (result.charAt(4) == 'a') {
So, what haven't I understood? According to me, I'm using an ajx function that sends a httpGet to the controller, which responds with a string. In javascript, I can work on a string like I did.
To use the string object, I haven't added any library. Should I have done that? I haven't found any information telling that.
Can you try this:
if (String(result).charAt(4) == 'a')
Also, as mentioned by #Musa, you should add a dataType attribute to the AJAX call:
$.ajax({
url: '#Url.Action("../Carte/Get")',
type: 'GET',
dataType: 'text',
data: {test: test},
success: function (result) {
if (result.charAt(4) == 'a') {
$("#LumAct").text(result.substr(0, 4) + " %");
alert('a');
}
If you check the jQuery.ajax api page you'll see that the first argument is an Object formatted to the dataType parameter. Honestly I'd console.log the result and see what it looks like. If you can't charAt() then the result is probably is not a string.