Ajax throwing error after calling controller - javascript

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.

Related

How to post js string to C# in ASP.NET Core MVC

I am new to ASP and I am trying to take a string in my JS code and post it to my controller so that I can use it to query my database.
JavaScript
function findEmployees(userCounty) {
$.ajax({
type: "POST",
dataType: "json",
url: '#Url.Action("Index", "Contact")',
data: JSON.stringify(userCounty),
contentType: "application/json",
success: function (response) {
alert(userCounty);
},
error: function (response) {
alert("failed");
}
});
}
Controller
[HttpPost]
public ActionResult Index (string userCounty)
{
var query = //use linq to query database
return View(query);
}
I only ever get the "success" alert when I use a JsonResult function in my Controller but I need it to eventually return a LINQ query to the View(); function and that hasn't worked when using a JsonResult function. Any ideas would be helpful. I don't necessarily have to use ajax if there is a better way. I just need a way to pass the string stored in userCounty to my controller.
Please change your controller method like this
[HttpPost]
public ActionResult Index([FromBody]string userCounty)
{
var query = //use linq to query database
return View(query);
}
For viewing the page, you'll need
[HttpGet]
public ActionResult Index()
{
return View();
}

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
}

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

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.

MVC How to pass data from view to model using Ajax

Hello I'm posted a question asking what to use to send information from a view to a model. I realize that the info needs to be send to the controller and then to my model. I got some code that send info from my view to my controller:
Here is the Ajax:
$(document).ready(function () {
$("#cmdSend").click(function () {
// Get he content fom the input box
var mydata = document.getElementById("cmdInput").value;
$.ajax({
type: "POST",
url: "/Terminal/processCommand",
data: { cmd: mydata }, // pass the data to the method in the Terminal Contoller
success: function (data) {
alert(data);
},
error: function (e) { alert(e); }
})
});
});
An this is the code in my controller:
[HttpPost]
public ActionResult processCommand(string cmd)
{
return Json(cmd);
}
I've tested it and send my input in json. However my problem is, I don't know how to take the string out of that and send it to my model. Please any help would be appreciated.
As stated in the comments to your question, the terminology you use is a little confusing, but if understood your question correctly, you want an action on your controller on the server to accept a 'command' and work with it.
The following post can be made, in order for the ajax post to successfully hit the action :
$('#cmdSend').click(function () {
var cmdInput = document.getElementById('cmdInput').value;
$.ajax({
url: 'terminal/sendInfo',
type: 'POST',
data: {cmd : cmdInput},
dataType: 'json',
success: function (data) {
//What you want to do with the returned string with data.cmd
}
});
});
The controller action would be like the following :
public class TerminalController : Controller
{
[HttpPost]
public JsonResult sendInfo(string cmd)
{
//Do what you want to do with 'cmd' here.
return Json(new { cmd = "Whatever you want to send" }, JsonRequestBehavior.AllowGet);
}
}
Hope this helps!

How to properly render the return of AJAX POST MVC 4

I'm using MVC 4 and I am trying to send a post request and I am getting a successful return from my controller with the resulting view in HTML form, but I'm not sure what to do with it at that point.
JS
$("form").submit(function (e) {
e.preventDefault();
if ($(this).valid()) {
$.ajax({
url: submitUrl, type: "POST", traditional: true,
data: { EventName: 'Name of event'},
success: function(data){
$("#content").html(data);
}
})
}
});
my controller
[HttpPost]
public ActionResult CreateEvent(EventModel model)
{
if(ModelState.IsValid)
{
return RedirectToAction("Index");
}
else
{
return View(model);
}
}
So you can see that my controller either returns a View or a RedirectToAction. In the success callback of my ajax call I am doing the following: $("#content").html(data);
But nothing seems to happen. Can someone help push me in the right direction of properly handling the return of the controller action.
Thank you so much!
If I understand correctly, you have a Create Event form on your page and you want to send an AJAX request to create a new event. Then you want to replace a section in your page #content with the results of the CreateEvent action.
It looks like your AJAX is set up correctly so that CreateEvent returns a successful response. I think you're now confused about the response. You have several options but let's choose two.
JSON response
[HttpPost]
public ActionResult CreateEvent(EventModel model)
{
if(ModelState.IsValid)
{
var event = service.CreateEvent(model); // however you create an event
return Json(event);
}
else
{
// model is not valid so return to original form
return View("Index", model);
}
...
Now you need to generate html markup from the JSON and insert it into #content.
$.ajax({
url: submitUrl, type: "POST", traditional: true,
data: { EventName: 'Name of event'},
success: function(data){
var obj = JSON.Parse(data);
var html; // build html with the obj containing server result
$("#content").html(html);
}
})
or HTML fragment
Instead of returning a full page with a Layout defined we'll return just a PartialView without Layout and all the head and script tags.
[HttpPost]
public ActionResult CreateEvent(EventModel model)
{
if(ModelState.IsValid)
{
var event = service.CreateEvent(model); // however you create an event
return PartialView("CreateEventResult", event);
}
else
{
// model is not valid so return to original form
return View("Index", model);
}
}
Now make a new partial view CreateEventResult.cshtml (Razor)
#model Namespace.EventModelResult
# {
Layout = null;
}
<div>
<!-- this stuff inserted into #content -->
#Model.Date
...
</div>
and the javascript is unchanged
$.ajax({
url: submitUrl, type: "POST", traditional: true,
data: { EventName: 'Name of event'},
success: function(data){
$("#content").html(data);
}
})
Edit:
If your Event creation fails for any reason after you have validated the input, you'll have to decide how you want to respond. One option is to add a response status to the object you return and just display that instead of the newly created Event.

Categories