So having a bit trouble figuring out how to successfully use AJAX to call a method and retrieve data. I am being asked to do this, not exactly sure why but I would usually just handle all this stuff in a MVC environment in the Controller. But for now I am asked to do this in AJAX. I have a ASPX file that I am simply trying to see work so i can move on. So far none of the stack overflow suggestions helped.
Here's what I currently have:
.ASPX/source
<script type="text/javascript">
$(document).ready(function () {
$("#go").click(function () {
$.ajax({
type: "GET",
url: "Default.aspx/ItemData",
processData: true,
data: {},
dataType: "json",
success: function () { alert("yay") },
error: function () { alert("nay") }
});
});
});
</script>
And then in my Default.aspx.cs file I have a method 'ItemData'
[WebMethod]
public static NextCrew.Models.Item ItemData(string cookieID)
{
Item item = new Item();
item.name = "Fred";
item.idx = 1;
item.completed = 1;
return item;
}
(Item is simple a Model withg 3 properties: Name(string), idx(int) and completed(int) )
I am having a hard time figuring out what I am doing wrong here. Can someone please write an example of what I am trying to do? Just a simple GET request that I can return an object (once I get done testing I want to be able to connect to a DB so I need it to be an object) using AJAX.
I can't tell what I am doing wrong but I have some ideas:
1)maybe my url in the ajax isn't formatted properly?
2)do i need to pass anything into data if I have a parameter?
3)is my get method in the correct .cs file?
UPDATE
I was informed I need to have a special class to handle this. I tried to then make a .asmx and the AJAX is still not being called. Hoping someone sees an error that I missed.
<script>
$(function () {
$.ajax({
type: "POST",
contentType: "application/json",
url: "WebService2.asmx/GetItems",
data: "{}",
dataType: 'Json',
success: function (result) {
// alert(result.d);
$.each(result.d, function (index, ele) {
$("#Myddl").append("<option value='" + ele.value + "'>" + ele.text + "</option>");
})
}
});
})
</script>
.asmx
public class WebService2 : System.Web.Services.WebService
{
[WebMethod]
public List<Item2> GetItems()
{
//suppose data comes from database
var result = new List<Item2>() {
new Item2{ text="one",value="one"},
new Item2{ text="two",value="two"},
new Item2{ text="three",value="three"}
};
return result;
}
public class Item2
{
public string text { get; set; }
public string value { get; set; }
}
}
Related
I am trying to post a string (the name of the href the user clicked on) using AJAX to my MVC controller (which it will then use to filter my table results according to the string).
Whilst I have managed to get it to post (at-least according to the alerts) on the AJAX side, it doesn't seem to arrive properly on the controller side and is seen as null in my quick error capture (the if statement).
Please excuse the useless naming conventions for the moment. I've been going through countless methods to try and fix this, so will name properly when I've got a proper solution :).
I've been at work for this for a long while now and can't seem to solve the conundrum so any help is appreciated please! I'm very new to AJAX and MVC in general so I'm hoping it's a minor mistake. :) (FYI I have tried both post and get and both seem to yield the same result?)
Controller:
[Authorize]
[HttpGet]
public ActionResult GetSafeItems(string yarp)
{
using (CBREntities2 dc = new CBREntities2())
{
if (yarp == null)
{
ViewBag.safeselected = yarp;
}
var safeItem = dc.Items.Where(a => a.Safe_ID == yarp).Select(s => new {
Serial_Number = s.Serial_Number,
Safe_ID = s.Safe_ID,
Date_of_Entry = s.Date_of_Entry,
Title_subject = s.Title_subject,
Document_Type = s.Document_Type,
Sender_of_Originator = s.Sender_of_Originator,
Reference_Number = s.Reference_Number,
Protective_Marking = s.Protective_Marking,
Number_recieved_produced = s.Number_recieved_produced,
copy_number = s.copy_number,
Status = s.Status,
Same_day_Loan = s.Same_day_Loan
}).ToList();
// var safeItems = dc.Items.Where(a => a.Safe_ID).Select(s => new { Safe_ID = s.Safe_ID, Department_ID = s.Department_ID, User_ID = s.User_ID }).ToList();
return Json(new { data = safeItem }, JsonRequestBehavior.AllowGet);
}
}
AJAX function (on View page):
$('.tablecontainer').on('click', 'a.safeLink', function (e) {
e.preventDefault();
var yarp = $(this).attr('safesel');
var selectedSafeZZ = JSON.stringify("SEC-1000");
$.ajax({
url: '/Home/GetSafeItems',
data: { 'yarp': JSON.stringify(yarp) },
type: "GET",
success: function (data) {
alert(yarp);
console.log("We WIN " + data)
},
error: function (xhr) {
alert("Boohooo");
}
});
})
** The Alert reveals the correct type: "SEC-1000"
But the console Log shows: WE WIN [Object object]??
I have tried something basic in a new mvc dummy project :
View page basic textbox and a button :
<input type="text" id="txt_test" value="test"/>
<button type="button" class="btn" onclick="test()">Test</button>
<script type="text/javascript">
function test()
{
var text = $("#txt_test")[0].value;
$.ajax({
url: '#Url.RouteUrl(new{ action="GetSafeItems", controller="Home"})',
// edit
// data: {yarp: JSON.stringify(text)},
data: {yarp: text},
type: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(data) {
// edit
// alert(JSON.stringify(data));
alert(data.data);
}});
}
</script>
Controller :
[HttpGet]
public ActionResult GetSafeItems(string yarp)
{
return Json(new {data = string.Format("Back end return : {0}",yarp)}
, JsonRequestBehavior.AllowGet);
}
Alert result => {"data":"Back end return : \"test\""}
It's a simple ajax call to a web method. You don't return a view, so I don't understand the use of
if (yarp == null)
{
ViewBag.safeselected = yarp;
}
Also I see an [Authorize] attribute, you perhaps use some authentication and I don't see any authentication header on your ajax call
Try this:
$.each(data, function (i) { console.log("We WIN " + data[i].Serial_Number )});
I am trying to get data from Active.cshtml.cs file using ajax call.
Here is the jquery code:
var turl = '/Active?handler=Clients/' + id;
$.ajax({
type: "GET",
url: turl,
dataType: "json",
success: function (result) {
alert(JSON.stringify(result));
});
Here is Active.cshtml.cs method
public JsonResult OnGetClients()
{
return new JsonResult("new result");
}
The status is 200 Ok, but it shows the entire webpage in response. Ideally it should return "new result" in Network tab of developer tools. Is it that I have Active.cshtml and Active.cshtml.cs in Pages that creates the confusion? How can I resolve it?
Thanks
For razor pages, you should be passing the parameter value(s) for your handler method in querystring.
This should work.
yourSiteBaseUrl/Index?handler=Clients&53
Assuming your OnGetClients has an id parameter.
public JsonResult OnGetClients(int id)
{
return new JsonResult("new result:"+id);
}
So your ajax code should look something like this
var id = 53;
var turl = '/Index?handler=Clients&id=' + id;
$.ajax({
type: "GET",
url: turl,
success: function (result) {
console.log(result);
}
});
Ajax doesn't send any strings to the controller.
Here's my function:
$(function () {
$('#btnAnswer').click(function () {
var code = $('#Answer').val();
$.ajax({
url: '#Url.Action("CheckAnswer", "Home")',
type: "POST",
data: code ,
datatype: "text",
success: function (resultFromFunct) {
$("#resultsBox").append(resultFromFunct);
}
});
$('#Answer').val('');
});
});
Here's my controller:
[HttpPost]
public string CheckAnswer(string answer)/
{
game.LogUserAnswer(Request.Cookies["user"].Value, answer);
return String.Format("<strong>{0}</strong>: {1} <br>", Request.Cookies["user"].Value, game.UserGuess(answer));
}
Ajax is correctly get into CheckAnswer method but answer is always null. I've tried other examples from stack, for instance Asp.Net Mvc JQuery ajax input parameters are null but always get null result. Do you have any thoughts of the cause?
Change your request parameters to data: { answer: code } in your request. It probably can not match code to the parameter on your action.
$(function () {
$('#btnAnswer').click(function () {
var code = $('#Answer').val();
$.ajax({
url: '#Url.Action("CheckAnswer", "Home")',
type: "POST",
data: { answer: code },
datatype: "text",
success: function (resultFromFunct) {
$("#resultsBox").append(resultFromFunct);
}
});
$('#Answer').val('');
});
});
I want to post JSON array to MVC controller through AJAX POST as:
$.ajax({
type: 'POST',
data: json.stringify(totaldata),
traditional:true,
url: '/Builder/Save',
success: function () {
alert("Playlist saved successfully!!");
}
})
and my controller code is have made array of one ViewModel & want to update those values as.
[HttpPost]
public ActionResult Save(IList<ItemEditViewModel> data,long playlistid=0, string Title="")
{
for (int i = 0; i < data.Count; i++)
{
var pc = db.PlaylistContents.FirstOrDefault(x => x.PlaylistContentId == data[i].ID);
if (pc == null)
{
pc = new PlaylistContent();
db.PlaylistContents.Add(pc);
}
pc.ContentMetaDataId = data[i].MetaID;
pc.PlaylistContentSequenceId = i + 1;
}
db.SaveChanges();
return RedirectToAction("Playlist", new {ID=playlistid });
}
But the Object is set to null in Controller.
My ViewModel is as,
public class ItemViewModel
{
public long ID{get;set;}
public long MetaID{get;set;}
}
Try adding the content type in ajax call,
contentType : 'application/json',
By default ajax sends with content type application/x-www-form-urlencoded; charset=UTF-8
Edit
also i dont know it this is a typo, json.stringify should be JSON.stringify
hope this helps.
$.ajax({
type: 'POST',
data: {"data":json.stringify(totaldata)},//You missed the format
traditional:true,
url: '/Builder/Save',
success: function () {
alert("Playlist saved successfully!!");
}
})
The Problem is solved & my application is working now properly.
I have just done JSON.stringify() on array elements & not the whole ajax data for posting.
the code is as written below:
var totaldata = { data: data, playlistid: parseInt(playlistid), Title: Title };
$.ajax({
type: 'POST',
data: { data: JSON.stringify(data), playlistid: parseInt(playlistid), Title: Title, deleted: JSON.stringify(deleted) },
traditional:true,
url: 'Save',
success: function (data) {
alert("Playlist saved successfully!!");
}
})
I'm trying to call the jQuery function $.get() to make a call to my WebMethod but it's only hitting the Page_Load event in the code behind. I can see the request being sent out in firebug to /admin/manage-users.aspx/deleteUser?u=user1 but it never hits the WebMethod.
jquery
$('#delete').each(function () {
$(this).click(function () {
var userName = $(this).closest('tr').find('span.userName').text();
$.get('/admin/manage-users.aspx/deleteUser', { u: userName });
});
});
aspx.cs
[WebMethod]
public void deleteUser() {
string userName = Request.QueryString["u"];
if(!string.IsNullOrEmpty(userName)) {
if(Membership.DeleteUser(userName))
Response.Redirect(Request.Url.ToString());
}
}
SOLUTION
I gave credit to bugz below because he pointed me in the right direction.
In order for your [WebMethod] to work your method within the aspx has to be static
Here is a link for more information
More Information
$.ajax({
type: "POST",
url: "'/admin/manage-users.aspx/deleteUser'",
data: "{'userName ' : '" + userName + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
//do something on success
},
error: function(ex) {
//do something on failure
}
});
Also on success if you are returning data or a variable make sure you use data.d for some reason when using jquery/ajax microsoft wants the .d at the end of the variable. This took me time to figure out.
Try this Im guessing when you debug the deleteUser Method never gets called.
var jqxhr = $.get("admin/manage-users.aspx/deleteUser", { userName: userName } function() {
alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });