Getting 404s when calling Actions in MVC3 with jQuery - c#

In my MVC3 app, I'm using $.ajax to call a method of type JsonResult to get data to be displayed:
function GetData(e) {
var ordersId = e.row.cells[0].innerHTML; //this is fine
$.ajax({
type: "POST",
url: "/Documents/GetDocumentData",
contentType: "application/json; charset=utf-8",
data: "{'id': '"+ordersId +"'}",
dataType: "json",
success: function (result) {
//load window
},
error: function (result) {
if (!result.success)
//show error
}
});
This is my Action:
[HttpPost]
public JsonResult GetDocumentData(string id)
{
//my code
return Json(new { success = true});
}
When im debugging on my development machine, it works fine. I deployed it to my test web server and i get '404 page not found dev/testwebsite/Documents/GetDocumentData' I should get this when debugging if something was wrong, but i dont. Why am I getting this error? Thanks

Your URL in the javascript is wrong, if that dev/testwebsite/Documents/GetDocumentData is the URL on the server.
You should be using #Url.Action() to automatically form those URLs in the cshtml page.
Example:
#Url.Action("actionName","controllerName" )
So, for your specific case, it would be:
#Url.Action( "GetDocumentData", "Documents" )
In the javascript, it would look like this:
function GetData(e) {
var ordersId = e.row.cells[0].innerHTML; //this is fine
$.ajax({
type: "POST",
url: '#Url.Action("GetDocumentData","Documents")',
contentType: "application/json; charset=utf-8",
data: "{'id': '"+ordersId +"'}",
dataType: "json",
success: function (result) {
//load window
},
error: function (result) {
if (!result.success)
//show error
}
});

Related

asp.net MVC JavaScript call to controller

I'm currently working on an ASP.Net MVC project.
I have a JavaScript function which takes an XML string as input. I would like to send this to the controller.
I have done so using an AJAX request, but in the controller the string is null.
View:
function save() {
var xml = scheduler.toXML();
alert(xml);
var url = '#Url.Action("Save", "Home")'
$.ajax({
url: url,
Type: "POST",
dataType: 'json',
async: false,
data: xml,
contentType: 'application/json; charset=utf-8',
success: function (data) { alert("OK");},
error: function (jqXHR, exception) {
alert('Error message.');
}
});
Controller:
public ActionResult Save(string xml)
{
Console.WriteLine(xml);
W6ViewModel viewModel = new W6ViewModel();
viewModel.engineers = db.W6ENGINEERS.ToList();
viewModel.tasks = db.W6TASKS.ToList();
viewModel.skills = db.W6TASKS_REQUIRED_SKILLS1.ToList();
var engList = new List<object>();
foreach (var engineer in viewModel.engineers)
{
engList.Add(new { key = engineer.ID, label = engineer.Name });
}
ViewBag.engineers = engList;
return View("Index", viewModel);
}
var xml = scheduler.toXML()
alert(xml):
Error Code (Sorry, wall of text):
[HttpRequestValidationException (0x80004005): A potentially dangerous Request.QueryString value was detected from the client (xmlString="<data><event>
Name your parameter like this:
function save() {
var xml = scheduler.toXML();
alert(xml);
var url = '#Url.Action("Save", "Home")';
$.ajax({
url: url,
Type: "POST",
dataType: 'json',
async: false,
data: { xml: xml},
contentType: 'application/json; charset=utf-8',
success: function (data) { alert("OK");},
error: function (jqXHR, exception) {
alert('Error message.');
}
});
Also put this tag above you controller action:
[ValidateInput(false)]
See the following ajax call:
$.ajax({
url: '#Url.Content("~/myaccount/CheckDuplicateEmailAddress")',
data: { "emailAddress": email },
async: false,
type: "post",
success: success,
error: error
});
And controller action is below. you need to send param as this:
data: { "emailAddress": email }
Remember case sensitivity and double quotes:
public bool CheckDuplicateEmailAddress(string emailAddress)
{
}

Retrieving Value post from $.ajax in ASP.NET MVC 4 Controller Method

I have write down a script as following
var reason = prompt("Please Enter the Reason", "");
if(reason != null)
{
// alert('you are here');
$.ajax({
type: "POST",
url: "/Controller/ActionMethod",
content: "application/json; charset=utf-8",
dataType: "json",
data: Json.stringify(reason),
success: function(){ alert('Data Sent');}
});
}
which works fine as it calls the ActionMethod from the controller but i am not being able to retrieve data taken with the help of prompt. within the controller.
I have tried
String reason = Request["reason"];
as well as i have tried to pass the data as argument in controller
public ActionResult ActionMethod(int id, string reason)
but in all cases reason is null. please tell me how can i retrieve the reason from the same.
thanks in advance
$.ajax({
type: 'POST',
url: "/Controller/ActionMethod",
data:{'reason':reason},
dataType: 'json',
success: function(jsonData) {
},
error: function(error) {
}
});
Your action maybe like this
[HttpPost]
public ActionResult ActionMethod(string reason){
...
return Json(obj);
}
this should work: Request.Form["reason"].

What is wrong with this JQuery AJAX code

I was facing some problem with AJAX code. I was using MVC3 for our project. My requirement is bind the dropdown value using AJAX when page load. What happens when loading the page, the AJAX request send to the controller properly and return back to the AJAX function and binds the exact values in dropdown. But sometimes (When page refreshed or first time load) its not binding retrieved value. Rather its showing default value. Pls see my code and suggest me where i am doing wrong.
Edit: Even i tried to use async property to false. Its not at all send to the controller action method for getting the data.
Code
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("GetUser", "Invoices")',
data: "{'id':" + JSON.stringify(currval) + "}",
dataType: "json",
async: true,
success: function (data) {
$("#User-" + curr).select2("data", { id: data.Value, Name: data.Text });
$(this).val(data.Value);
}
});
Thanks,
Let's say your Action method is below
public JsonResult hello(int id)
{
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
and JQuery should be like below
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var currval = 2;
$.ajax({
url: 'URl',
async: true,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ id: currval }),
success: function (data) {
}
});
});
</script>
You are declaring your data property incorrectly. Try this:
data: { id: currval },

List of GUIDs JSON being sent to MVC controller via GET is empty upon arrival, POST works

I am sending a collection of GUID-like objects to my MVC controller like so:
$.ajax({
type: 'GET',
url: 'http://localhost:61975/Song/GetByIds',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: {
songIds: JSON.stringify(songIds)
},
success: function (data) {
},
error: function(error) {
console.error(error);
}
});
The data being sent in my request header looks like:
songIds:["6cb44f55-9fd5-4540-9b11-75ccce816d67"]
and my MVC3 controller method looks like:
[HttpGet]
public ActionResult GetByIds(List<Guid> songIds)
{
SongManager songManager = new SongManager(SongDao, PlaylistDao, PlaylistItemDao);
IList<Song> songs = songManager.GetByIds(songIds);
return new JsonDataContractActionResult(songs);
}
In this implementation I receive a non-null List object, but it is always empty. What's my mistake?
EDIT: If I POST like this instead of GET it works fine. How come??
$.ajax({
type: 'POST',
url: 'http://localhost:61975/Song/GetByIds',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
songIds: songIds
}),
success: function (data) {
loadedSongs = loadedSongs;
if (callback) {
callback(data);
}
},
error: function(error) {
console.error(error);
}
});
You should try to use "traditional" option set to true for your jQuery Ajax request.
Refer to documentation for more details : http://api.jquery.com/jQuery.ajax/
And you should also remove the JSON.Stringify part.
Can you try this out and let me know if it worked out for you ?
I Did a test on my end and it works just fine.
$.ajax({
type: 'GET',
url: 'http://localhost:61975/Song/GetByIds',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
traditional: true, //// traditional option to true
data: {
songIds: songIds /// no JSON.stringify
},
success: function (data) {
},
error: function(error) {
console.error(error);
}
});

jquery 1.5 ajax call giving invalid argument for webmethod in a handler

I am getting a problem in calling a webmethod inside my http handler. The jquery.js file opens up at some random place and gives a prompt "Invalid Argument"
Code is as follows:
JS:
var src = "MyHandler.axd";
var id = "1234566";
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: src + "/MyMethod?key=" + id,
success: function (msgObj) {
var msg = msgObj.d;
},
error: function (e) {
alert("Error");
}
});
C#
[System.Web.Services.WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string MyMethod(string key)
{
return someLogic;
}
And because of which the ProcessRequest method is being called for the ajax call.
Even tried it with following
Removed httpget and responseformat from c# code.
JS
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: src + "/MyMethod",
data: "{ 'key':'"+ id +"'}",
dataType: "json",
success: function (msgObj) {
debugger;
var msg = msgObj.d;
},
error: function (e) {
debugger;
}
});
Well, not able to find any solution or reason why this behavior!
Kept the same webmethod in a page and its working fine. So added logic to handle the ajax call in process request only. works like a charm.

Categories

Resources