How to make AJAX calls - javascript

I am aware this question has been answered before but I am somehow unable to hit an action within my controller.
Here is the Action
public JsonResult GetUpdate()
{
//get a list of valid elements
var result = getContent();
return Json(result, JsonRequestBehavior.AllowGet);
}
In my script:
$.ajax({
type: 'GET',
url: '#Url.Action("GetUpdate")',
dataType: 'json',
success: function (constraints) {
alert("Application updated");
},
error: function (ex) {
alert('Failed to retrieve update.' + ex);
}
});
Using fiddler I can hit GetUpdate but from the browser the Ajax call fails. Am I correctly accessing the URL?
Update:
The following is the error message:
"NetworkError: 404 Not Found - protocol://localhost:port/Controller/#Url.Action(%22GetUpdate%22)"
The following works through Fiddle:
protocol://localhost:port/Controller/GetUpdate

Razor code (C# and all other server-side script) is only executed from .cshtml files, therefore C# and Razor can't be used in .js files.
'#Url.Action("GetUpdate")' doesn't generate a URL, it's just a string, therefore you are trying to request protocol://domain:port/Controller#Url.Action("GetUpdate") which doesn't exist.
Here's what you can do:
In the .cshtml file you can store the generated URL in a JavaScript variable and pass it to the external JS file.
You can move your external JavaScript to the .cshtml file so you can use Razor.
use a relative string path like /Controller/GetUpdate
I would recommend the first one.

You can try this out,where _ApplicationPath is protocol://localhost:port/
$.ajax({
type: 'GET',
url: _ApplicationPath + "/ControllerName/GetUpdate",
dataType: 'json',
success: function (constraints) {
alert("Application updated");
},
error: function (ex) {
alert('Failed to retrieve update.' + ex);
}
});

Related

Every $.ajax url returns 404 Not Found. What is the correct path? How can I troubleshoot this?

I want to do a $.ajax({type: "POST" to a method found in \Pages\PCL\PCL_Index.cshtml.cs. The method signature is public void OnPostUpdateList(int listId, string itemName, bool isRemoving). My attempts always return: POST https://localhost:44360/PCL/OnPostUpdateList 404 (Not Found) or some variety of that 404 message. Here is my jquery:
$.ajax({
type: "POST",
url: "/PCL/OnPostUpdateList",
data: { listId: listId, itemName: itemName, isRemoving: isRemovingChecked },
success: function (result) {
if (result.success) {
console.log(result);
}
else {
alert("Error: " + result.errorMessage);
}
},
error: function (xhr, status, error) {
alert(error);
}
And here are the url: paths I've tried:
url: "/PCL/OnPostUpdateList",
url: "PCL/OnPostUpdateList",
url: "/PCL/UpdateList",
url: "/OnPostUpdateList",
url: "/PCL/?handler=OnPostUpdateList",
url: "/PCL/?handler=UpdateList",
url: "/PCL/PCL_Index?handler=UpdateList",
url: "/PCL/PCL_Index?handler=OnPostUpdateList",
url: '#Url.Page("PCL/UpdateList")',
url: '#Url.Page("PCL/OnPostUpdateList")',
url: '#Url.Page("/PCL/PCL_Index/OnPostUpdateList", "listId", "item", "action")',
url: '#Url.Page("/PCL/PCL_Index/UpdateList", "listId", "itemName", "isRemoving")',
I've added this attribute to my model but it doesn't help: [IgnoreAntiforgeryToken(Order = 1001)].
I was able to reach the wrong post method public async Task<IActionResult> OnPostAsync() used to post the entire form, but that is not wanted. That method was reached when I used these:
url: '#Url.Action("UpdateList", "PCL_Index")',
url: '#Url.Action("OnPostUpdateList", "PCL_Index")',
How can I best troubleshoot this frustrating issue? What is the correct url path?
I'm using ASP.Net Core 6 Razor Pages. My goal is to allow users to add or remove items from drop-down select lists on the page (and the underlying database lookup tables). I want to let them modify lists without updating the entire form that the select lists are within. When the user clicks a button next to each select list a bootstrap modal form pops up allowing the user to add or remove list items. The ajax code is called when the user clicks Save Changes on the modal window.
EDIT: I have just found the problem was caused by some information I did not provide since it was overlooked. Within IIS Express I had set up an App URL of localhost:64373/Lab. So, I have been missing Lab/ from my path. In the future I can post a more complete answer, unless someone else would like to try given this new information.
The problem is solved by using #Url.Content("~/")
To troubleshoot this issue, look at the url (of the page) in each location where the application runs. Here, the deployed url is: https://(Host Name or Domain Name)/PCL. During development the url is: https://localhost:(Your Port)/Lab/PCL. Notice the addition of /Lab on the development machine. This App URL is set in the project properties Launch Profiles for IIS Express.
To resolve the different paths to the application root make use of #Url.Content("~/"). Unfortunately, javascript does not understand #Url.Content("~/") so we build a javascript function called expandPath:
function expandPath(path) {
if (!path) return undefined; if (path.substring(0, 2) === "~/") {
const root = $("body").attr("data-rooturl");
path = root + path.substring(2);
} return path;
}
which points to the body element of the _Layout.cshtml page:
<body data-rooturl="#Url.Content("~/")">
Finally, we call expandPath in the ajax url:
$.ajax({
type: "POST",
url: expandPath("~/PCL?handler=UpdateList"),
data: { listId: listId, itemName: itemName, isRemoving: isRemovingChecked },
success: function (result) {
if (result.success) {
console.log(result);
}
else {
alert("Error: " + result.errorMessage);
}
},
error: function (xhr, status, error) {
alert(error);
}
Notice the use of ?handler=UpdateList to point the method public void OnPostUpdateList. ?handler= is used in the queryString because we want to avoid calling the default OnPost method to prevent posting the full page to the server.

Upload Attachment and some additional parameters to MVC Controller

I have a MVC Controller with the following signature:-
[HttpPost]
public async Task<JsonResult> SaveBrochureAsAttachment(Guid listingId, HttpPostedFileWrapper attachmentFile)
{
///some logic
}
How do I make an ajax call and send the file attachment and additional listingId parameter. Currently I am only able to send the attachment like this:-
var uploadFile = function () {
if ($('#attachmentFile').val()) {
}
else {
alert('No File Uploaded');
return;
}
var formData = new FormData($('#uploadForm')[0]);
$.ajax({
url: '/Listing/SaveBrochureAsAttachment',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert('File Uploaded');
},
error: function (jqXHR, textStatus, errorThrown) {
$("#FileUpload").replaceWith($("#FileUpload").val('').clone(true));
alert('File Uploaded Error');
},
cache: false,
contentType: false,
processData: false
});
return false;
}
Currently as you folks can see I am only able to send the attachment. How do I also send the Guid listingId to match the controller signature.
Try adding another formdata parameter:
formData.append("listingId", guidValue);
Provided you have the guid value accessible. You can use this to generate one from the client. Or create one from the server:
var guidValue = '#Guid.NewGuid()';
one approach would be to your controller accept viewmodel (a class) which contains different property you need. and use formdata.append required stuff to post to the server.
On Server side; you will need to use modelbinder so that you will get required stuff populated.
Refernce for modelbinder : https://www.dotnetcurry.com/aspnet-mvc/1261/custom-model-binder-aspnet-mvc
you can get more on google. :)

MVC 5 generate form data with AJAX

I need a way to generate a new unique id for a user when a person focuses out of a textbox. I am using MVC 5 for this application. Here is my controller, everything in the controller has been unit tested and it does return the string value that I need.
Controller. I was able to visit that URL, and I did download a JSON file with the correct data.
public ActionResult GetNewId()
{
string newId = utils.newEmployeeId();
return Json(new {eId = newId}, JsonRequestBehavior.AllowGet);
}
Javascript, JQuery call to that controller. I do not know how to properly reference the ActionResult. I keep getting undefined errors on eId.
$(function () {
$('#employeeId').focusout(function () {
if($("#employeeId").val() === "NP")
$.ajax({
type: 'GET',
url: '#Html.ActionLink("GetNewId", "Employees")',
data: { 'eId': eId },
dataType: 'json',
success: function (response) {
$("#employeeId").val(eId);
},
error: function (response) {
alert(response);
}
});
});
});
The problem is with yout ajax request:
1.you need to change the url in the reuqest but it like this
{{yourcontroller}/GetNewId}
2.remove the "data: { 'eId': eId }" you dont need it, youre not posting anything to the server.
change your $("#employeeId").val(eId); to
$("#employeeId").val(response.eId);
this will 100% work

404 error when making ajax call to asp.net MVC controller

I'm trying to make an ajax request to an MVC controller but I keep getting a 404 error whenever I try execute my script.
Failed to load resource: the server responded with a status of 404 ()
https://localhost:44301/LocationMapping/Test
My request just returns error get from the code snippet below.
The structure of the relevant files in my project are
View where request is called -> courselister/index.cshtml
View's Controller -> CourseListerController.cs
My Controller for handling Ajax requests from the above view-> LocationMappingController.cs
The reason I am handling the requests from a different controller is because several views will use the same requests and so it seems better to keep these all together in LocationMappingController.
Here is the code for my ajax request
$(document).ready(function () {
$.ajax({
url: "/LocationMapping/Test",
type: "GET",
dataType: "json",
data: {},
error: function (error) {
alert('error get');
},
success: function (data) {
alert('GET success');
alert(data);
}
});
});
Here is the code in the LocationMapping Controller
public JsonResult Test() {
{
return Json("Get Test", JsonRequestBehavior.AllowGet);
}
My current theory is that the server cannot find the route /LocationMapping/Test because it is not it the view's controller (CourseListerController.cs). It has taken a long time for me already to find a solution and so I am turning to the SO community to help.
Any help is appreciated.
Update: I tried creating a new controller and a view associated with it as follows,
TestAjaxController.cs
public ActionResult Index()
{
return View();
}
public JsonResult GetResponse(string str)
{
return Json(str, JsonRequestBehavior.AllowGet);
}
TestAjaxController/Index.cshtml
<div>
<h1>Test Ajax Page: Location Mapping</h1>
<button onclick="callAjax()">Click Me</button>
<script>
//document.ready(function () {
console.log('jquery loaded');
function callAjax() {
$(document).ready(function () {
alert("called");
jQuery.ajax({
url: "/TestAjax/GetResponse",
type: "GET",
dataType: "json",
data: { str: "this is the string I want to get as a response" },
error: function () {
alert("Error occurred calling GetResponse");
},
success: function (data) {
alert(data);
}
});
});
}
</script>
</div>
and this works! I get prompted with the "this is the string I want to get as a response". I don't understand why it works when my other controller will not..
Faced the same issue. Closed the localhost tab in browser and ran start without debugging. I was able to view the JSON data in the route.

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
}

Categories