Using $.ajax or $.post to call MVC 5 Controller method - javascript

I'm trying to set up what should be a very simple call from an MVC page to a controller using JavaScript. This is my Controller:
Imports System.Web.Mvc
Namespace Controllers
Public Class DataController
Inherits Controller
Function Index() As ActionResult
Return View()
End Function
<HttpPost>
Function SaveData(payload As String) As String
If payload IsNot Nothing AndAlso payload.Length > 0 Then
Return "Good"
Else
Return "Bad"
End If
End Function
End Class
End Namespace
this is my View (Index.vbhtml):
#Code
ViewData("Title") = "Index"
End Code
<h2>Index</h2>
#Code
Html.BeginForm()
#:Save Data
Html.EndForm()
End Code
and this is my JavaScript (included via the _layout.vbhtml file):
function SaveData() {
var payload = "TEST_DATA_GOES_HERE";
// Calls controller correctly but data is null
$.ajax({
url: "/Data/SaveData",
type: "POST",
processData: false,
dataType: String,
data: { payload: payload }
})
.done(function () { alert('Application saved.'); })
.fail(function () { alert('Application failed to save.'); });
// Returns a 500 error
$.post("/Data/SaveData", { Payload: payload }, function (data) { alert('Application saved. ' + data); }, "String");
// Calls controller correctly but data is null
$.post("/Data/SaveData", payload, function () { alert('Application saved.' + data); }, "String");
}
Everything connects up nicely when debugging but the payload variable arrives as Nothing in the SaveData function. I've tried using $.post but with similar problems and all the references I've found to using either method simply assume that it will work first time without error and don't have any troubleshooting tips.
How do you configure the $.ajax or $.post functions to correctly call a controller and pass a simple string?

You need to set processData to true as you are sending an object which will need to be converted to a querystring.
From the API:
ProcessData
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
http://api.jquery.com/jQuery.ajax/

Thanks to the answer form Rory this is what I ended up with:
Controller:
<HttpPost>
Function SaveData(payload As String) As Boolean
If payload IsNot Nothing AndAlso payload.Length > 0 Then
Return True
Else
Return False
End If
End Function
JavaScript:
function SaveData() {
var payload = "TEST_DATA_GOES_HERE";
// Calls controller correctly but data is null
$.ajax({
url: "/Data/SaveData/",
type: "POST",
data: { payload: payload }
})
.done(function () { alert('Application saved.'); })
.fail(function () { alert('Application failed to save.'); });
}
Note that the $.ajax call doesn't have the processData or dataType elements and that the name of the variable matches the case of the parameter.
However what I found out is that my real problem was actually caused by passing XML as a string in this call. The XML cannot be simply passed as is in the query string. If you do that it arrives as null most likely because the MVC model binder can't process the resulting bad querystring.

Related

HttpPost in MVC Controller not being called through Ajax POST

I have a controller (InformationTechnologyController). That controller contains an action (LocationChangeRequest). That action takes an optional parameter(id).
public ActionResult LocationChangeRequest(ChangeRequestType id = ChangeRequestType.WithinDepartment)
That action returns a view with the current model data.
return View(locationChangeRequest);
Within that view, there's a function that performs an ajax post (code below) to search for employee information.
Employee Search 1
The url to reach that view is:
http:// [not relavant here] /InformationTechnology/LocationChangeRequest
When a user attempts to reach that view using a route parameter, the Employee Search function does not perform.
The url to reach the view with the routing parameter is:
http:// [not relavant here] /InformationTechnology/LocationChangeRequest/1
What I discovered is the HttpPost method in the InformationTechnology controller is not being hit when using the /1 parameter in the path. Athough it seems to have to do with the parameter in the path, I can't seem to figure out how to solve the problem.
Any advice on how to handle hitting the HttpPost through the url with the parameter would be appreciated.
The HttpPost code is as follows:
[HttpPost]
public JsonResult SearchUser(string term)
{
...
return Json(results, JsonRequestBehavior.AllowGet);
}
The javascript code is as follows:
$.ajax({
url: searchUserUrl,
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data,
function (item) {
return { label: item.Name, value: item.HexKey }; }));
},
error: function (xhr, error) {
console.debug(xhr); console.debug(error);}
})
You need to define a global variable for using the $ as below.
var $=jQuery.noConflict();

MVC5 Controller not receiving JSON Object

I have a controller with method as follows:
public JsonResult Save(List<BlogInfo> list)
{
return Json(new { Data = "" }, JsonRequestBehavior.AllowGet);
}
And I have an ajax post from the client as follows:
$.ajax({
url: "Home/Save",
type: "post",
contentType: "application/json",
data: ko.mapping.toJSON(ViewModel),
success: function (response) {
alert(response.Status);
}
});
My problem is that list parameter to the controller is always null. I tried changing it to string instead of List but that is also null.
Using Fiddler, I can see that the JSON is being pass as follows:
{"Data":[{"Id":1,"Title":"Sudoku Solver","Description":"Programmed Sudoku Solver","Tags":["programming","sudoku"]},{"Id":2,"Title":"Picnic","Description":"Went to millpoint","Tags":["picnic"]},{"Id":0,"Title":"Title","Description":"Description","Tags":[]}]}
The JSON you have shown doesn't represent an array, so you cannot possibly expect to bind it to a list on the server. To achieve that make sure that you are sending an array of objects from the client:
data: ko.mapping.toJSON(ViewModel.Data);
Here we take the ViewModel.Data property which represents an array so that we send only the desired JSON:
[{"Id":1,"Title":"Sudoku Solver","Description":"Programmed Sudoku Solver","Tags":["programming","sudoku"]},{"Id":2,"Title":"Picnic","Description":‌​"Went to millpoint","Tags":["picnic"]},{"Id":0,"Title":"Title","Description":"Description‌​","Tags":[]}]

Call c# function with javascript code

I would like to call a code behind function from the client side.
The function cannot be static - should modified unstatic variabels.
I was able to create a non-visible button, and when I need that function I demonstrate a click on that btn.
How can I send parameters to that code behind function?
$.ajax({
url: '/ControllerName/ActionName',
type: "GET",
data: { param1: val1 },
success: function (res) {
alert(res) // res is results that came from function
}
});
This is the client side to call backend method. The server side to accept this request:
public ActionResult ActionName(string param1)
{
return View(param1);
}
In this case, we used jQuery, the javascript plugin, and we used AJAX request, also sending parameters.
Using MVC and jQuery
Client Side ( Using Razor )
$.ajax({
url: '#Url.Action("ActionName","ControllerName",new{parameters})',
type: "GET",
contentType: "application/json",
data: { param1: val1 },
success: function (res) {
alert(res) // res is results that came from function
},
error: function (jqXHR, error, errorThrown) {
console.log('An error as occured');
},
});
Server Side
[HttpGet]
public JsonResult ActionName(string param1)
{
return Json(param1, JsonRequestBehavior.AllowGet);
}
Note: HttpGet Verb is the default verb for every ActionResult/JsonResult
the button have a CommandArgument attribute that you can use to send a value to that function and you can read it as follow :
public void yourFunction(object sender,Eventargs e)
{
string args = ((LinkButton)sender).CommandArgument.ToString();
// rest of code here
}

Ajax throwing error after calling controller

I am having some issues calling a controller method from my jquery ajax. The controller method is called and the data servername is passed in correctly. But, before my controller can return anything to the jquery, the jquery enters the error state.
Here is my jquery and controller code snippets:
$.ajax({
type: 'POST',
url: '#Url.Action("serverLookup", "QC")',
dataType: 'text',
data: { 'serverName': servername },
success: function (result) {
alert(result);
debugger;
},
error: function (result) {
debugger;
}
});
[HttpPost]
public ActionResult serverLookup(string serverName)
{
string data = myMethod.getData();
return Content(data);
}
On top of everything. The result value given when the error is reached is not helpful at all either.
Send your response back as JsonResult
[HttpPost]
public JsonResult serverLookup(string serverName)
{
string data = myMethod.getData();
return Json(data);
}
Return a Json:
return Json(new { result: data });
When you make an AJAX request to the controller, it needs a JsonResult.
I suppose that Your Content() return html. In that case You have to change dataType to html, Or change it according to your response.

Json object not being passed to web api method

I've been at this for hours now and still not got it right... someone please put me out of my misery!
javascript:
var calcParams = {}
calcParams.calcName="gwp_mat";
calcParams.components=124.332;
//return manager.impactCalc(calcName, componentArray)
return postData("{calcParams2:" + JSON.stringify(calcParams) + "}")
.then(querySucceeded)
.fail(queryFailed);
function postData(cp) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/api/breeze/testCalc",
data: cp,
success: function (data) {
alert(data);
return data;
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
}
});
}
model:
Public Class calcParams2
Public calcName As String
Public calcNumber As Double
End Class
Server code:
<System.Web.Services.WebMethod()> _
Public Function testCalc(cp As calcParams2) As Double
Dim c As New calcs
Return cp.calcNumber
End Function
If I debug it, the "cp" parameter in the javascript postData function is:
"{calcParams2:{"calcName":"gwp_mat","components":124.332}}"
and yet in my web method, calcname is "nothing" and components is "0.0"
If I don't use JSON.Stringify I get a null object in my web method. I think I had one version of code where the calcName was passed but the components value was still zero. That was when I just called "return postData(JSON.stringify(calcParams))" I think.
You only need to send the object parameters in the JSON:
return postData(JSON.stringify(calcParams)) ...
However your JQuery Object needs to have the same parameter names as your Server object. Change your server object to be:
Public Class calcParams2
Public calcName As String
Public components As Double
End Class
OR change your client object:
var calcParams = {}
calcParams.calcName="gwp_mat";
calcParams.calcNumber=124.332;

Categories