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

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"].

Related

ajax POST sending null

I originally wrote the call as a GET but found a limitation with the length of the URI. Ideally, the call will take an object and turns it into a JSON format string, then sends it to a controller which will encrypt that string. The controller will send back a true/false if it succeeded.
My problem with POST, once it reaches the controller, the data parameter set from the ajax is null.
Here is the ajax/js:
var encActionURL = '#Url.Action("Encrypt", "Home")';
$.ajax({
url: encActionURL,
type: "POST",
contentType: "application/json; charset=utf-8;",
dataType: "json",
async: true,
traditional: true,
data: { jsonDoc: JSON.stringify(jsonDataFile) },
success: /*OnSuccess*/ function (result) {
// DO STUFF;
}
});
Here is the controller:
[HttpPost]
public bool Encrypt(string jsonDoc)
{
return serverConnection.Encrypt();
}
Note that, when I simply change the type to 'GET', it works great but when the form gets too long, it throws a 414 status error.
Most of the fixes found that I seem to have is the 'application/json'. I've also set ajax to traditional.
After going through a rabbit-hole of security tokens and validating forms, it wasn't any of that... this might be a solution for anyone using ASP.NET Core 2.1 MVC (5?) or just in general. Could have been a syntax mistake, return type mistake, or a combination.
New Ajax
$.ajax({
url: encActionURL,
type: "POST",
data: { 'jsonDoc': JSON.stringify(jsonDataFile) }, // NOTICE the single quotes on jsonDoc
cache: false,
success: /*OnSuccess*/ function (result) {
// DO STUFF;
}
});
New Controller
[HttpPost]
public ActionResult EncryptJSON(string jsonDoc) // Switch to ActionResult, formerly JsonResult
{
return Json(serverConnection.Encrypt());
}

Ajax error when there's a parameter in url

I have a ajax code that fills a dropdownlist and I use mvc c#.
When I call to my method from ajax and I have an url in the directions bar without parameters the code works correctly, but if I have a parameter in url in the directions bar this not working and appears this error:
"{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}".
Here's my code:
$.ajax({
url:"../Records/myList",
type: "POST",
dataType: 'json',
contentType: 'application/json',
// data: JSON.stringify(Data),
success: function (resul) {
Function(resul);
},
error: function (message) {
}
});
My url: http://localhost:123/Record/EditRecord ->> so it's works
My other url: http://localhost:123/Record/EditRecord/1 ->> It does not work like this
Thanks in advance.
From given second URL (which doesn't work) I assume that you want to use jQuery AJAX with HttpGet method. The URL pattern matches this route:
http://localhost:123/{controller}/{action}/{id}
which id treated as UrlParameter.
Hence you need to use action argument & data representing URL parameter values, like this example:
Controller
[HttpGet]
public ActionResult EditRecord(int id)
{
// other stuff
}
View (JS)
$.ajax({
url: "/Record/EditRecord",
type: "GET",
dataType: 'json', // response type
contentType: 'application/x-www-form-urlencoded; charset=utf-8', // header content type
data: { id: 1 },
processData: true, // this is important to use in GET methods
success: function (result) {
Function(result);
},
error: function (message) {
// throw error
}
});
Alternatively a direct usage of URL parameter is applicable for GET methods without specifying data content:
View (JS)
$.ajax({
url: "Record/EditRecord/1",
type: "GET",
processData: true, // this is important to use in GET methods
success: function (result) {
Function(result);
},
error: function (message) {
// throw error
}
});
NB: Use jQuery.get for simplified version:
$.get("/Record/EditRecord/1", function (result) {
Function(result);
}, "json").error(function (message) { // throw error
});
PS: This is an example for HTTP POST request if you're looking for proper POST method with AJAX.
Controller
[HttpPost]
public ActionResult EditRecord(Record rec)
{
// other stuff
}
View (JS)
$.ajax({
url: "/Record/EditRecord",
type: "POST",
dataType: 'json', // response type
contentType: 'application/json; charset=utf-8', // header content type
data: JSON.stringify({ rec: { id: 1, name: 'XXXX', ... }}),
success: function (result) {
Function(result);
},
error: function (message) {
// throw error
}
});
Reference:
Do GET, POST, PUT, DELETE in ASP.NET MVC with jQuery AJAX
i cant see any fault in the code but i suggest to try let the param come with it's name at server either if you choose to use data propery (of ajax function):
{key1: 'value1', key2: 'value2'}
or you use string query:
page?name=ferret&color=purple
bacuse you've just say that first method was work i assume there is no need to check POST/GET method.
EDIT:
be award to this.

.NET MVC posting multiple parameters to controller using ajax

I know this question has been asked many times, I relly tried to follow many examples but every time, I fail for an unknown reason. So I'm going to show you my example a (very simple one) and I need someone to tell me what did I do wrong.
Starting with the controller (its name is Recherche) method:
public int getNote(string a,string b)
{
if(string.IsNullOrEmpty(a))
return 1;
else return 0;
}
As you can see I didn't use the variable b, but who cares it's just an example.
Now for the ajax method:
$.ajax({
type: "POST",
url: "/Recherche/getNote",
coententType: 'application/json',
dataType: 'json',
data:JSON.stringify({a:"a",b:"b"}),
success: successFunc,
});
function successFunc(data) {
document.getElementById('note').innerHTML = data;}
Try this
var a1='';
var b1='';
$.ajax({
type: "POST",
url: "/Recherche/getNote",
coententType: 'application/json',
dataType: 'json',
data:JSON.stringify({a:a1,b:b1}),
contentType: "application/json; charset=utf-8",
processData: false,
success: function (data) {
document.getElementById('note').innerHTML = data;
},
error: function (response) {
if (response != 1) {
alert("Error!!!!");
}
}
});
Controller
[HttpPost]
[WebMethod]
public ActionResult getNote(string a,string b)
{
if (a== null && b==null) return Json(0);
//Some Action send Result
return Json(data, JsonRequestBehavior.AllowGet);
}

getting data from controller in error function of jquery ajax -- Asp.net MVC

I have a jquery ajax script like following
$.ajax({
type: "POST",
url: "Main/receive", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'p':$("#txtname").val() }),
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
// Or if you are returning something
},
error: function (result) {
alert('Oh no zzzz:('+result.responseText);
}
});
And I am calling to Controller action method. The data is sending to the controller's action method and I am also receiving data from the controller. But the data that I am receiving is inside the error function of jquery ajax.
I want it to be inside the success function.
Why my success function is not getting called.
Following is my controller's action method,
[HttpPost]
public string receive(string p)
{
ViewBag.name = p;
return p;
}
The reason for the error is that you have specified that the returned data type be json (in the line dataType: "json",) but you method returns text. You have 2 options.
Change the controller method to return json using return Json(p);
Change the ajax option to dataType: "text", or just omit it
However you can improve your script as noted below
$.ajax({
type: "POST",
url: '#Url.Action("receive", "Main")', // don't hardcode url's
data: { p: $("#txtname").val() }, // no need to stringify (delete the contentType: option)
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no zzzz:('+result.responseText);
}
});
or even simpler
$.post('#Url.Action("receive", "Main")', { p: $("#txtname").val() }, function(result) {
alert('Yay! It worked!');
}).fail(function(result) {
alert('Oh no zzzz:('+result.responseText);
});
Notes: You should always use #Url.Action() to generate the correct urls, and it is not necessary in this case to stringify the data (but you need to remove the contentType: line so it used the default application/x-www-form-urlencoded; charset=UTF-8)
In addition, this is not strictly a POST (your not changing data on the server - but I assume this is just for testing). And there is no point in the line ViewBag.name = p; - it does nothing in your context, and as soon as you return from the method, ViewBag is lost anyway.
try to change your controller code as follows
[HttpPost]
public ActionResult List(string p)
{
ViewBag.name = p;
return Json(ViewBag);
}
Your controller method should look like this:
[HttpPost]
public ActionResult receive(string p)
{
return Json(p);
}

Getting 404s when calling Actions in MVC3 with jQuery

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
}
});

Categories

Resources