The resource cannot be found in Ajax function - c#

I'm using C# asp.net mvc.
I wrote a Ajax function in my Home controller - > index.cshtml.
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'POST',
dataType: 'html',
url: '#Url.Action("getAlerts","Home")',
data: ({}),
success: function (data) {
$('#alertList').html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
</script>
this is my function in Home controller
public IList<tblInsurance> getAlertsIns()
{
var query = (from i in db.tblInsurances
where i.status == true && i.EndDate <= DateTime.Today.AddDays(7)
select i).ToList(); ;
return query;
}
public string getAlerts()
{
string htmlval = "";
var InsExpirList = getAlertsIns();
if (InsExpirList != null)
{
foreach (var item in InsExpirList)
{
htmlval += item.tblContractor.Fname + " " + item.EndDate + "<br />";
}
}
return htmlval;
}
But ther is error and it says " The resource cannot be found."
POST http://localhost:49368/Home/getAlerts 404 Not Found
what is wrong with my code?

If you want your controller action to accept POSTs, you must decorate it with an attribute specifying that fact:
[HttpPost]
public string getAlerts()
{
// ...
}
In this case, however, it seems like a GET request would be more appropriate (your action is called getAlerts after all). If that's the case you can omit the accepted verb, or use [HttpGet] instead. You would also have to change your AJAX request:
$.ajax({
type: 'GET',
dataType: 'html',
url: '#Url.Action("getAlerts","Home")',
/* ... */
});

Related

ASP.NET MVC AJAX Call to Controller Not Returning any Data

I'm trying to call an ASP.NET MVC controller using an AJAX Call. Basically I want to return customer details based on the ID selected from a dropdownlist. On debugging, controller is being hit and returning data in JSON format however, on debugging javascript, it never gets to success, failure or error.
Here is the code I'm using:
View:
<script type="text/javascript">
$(document).ready(function () {
$("#CustomerId").select2({
placeholder: "Select a customer"
});
$("#CustomerId").change(function () {
var param = $("#CustomerId Option:Selected").val();
$.ajax({
type: 'GET',
data: { Id: param },
url: '/QuickInvoices/GetCustDetails',
success: {
function(response) {
if (response != null) {
alert("hello");
$('customer_CompanyName').val(response.CompanyName);
}
else {
alert("something went wrong!");
}
}
},
failure: function (response) {
alert('failed');
},
error: function (response) {
alert('error' + response.responseText);
}
});
});
});
</script>
Controller:
[HttpGet]
public JsonResult GetCustDetails(int Id)
{
Customer customer = db.Customers.Where(x => x.Id == Id)
.SingleOrDefault<Customer>();
return Json(customer, JsonRequestBehavior.AllowGet);
}
Can someone help please?
Please try below Code sample and check the Request & Response of network tab
you will get batter Idea
$(document).ready(function () {
$("#CustomerId").select2({
placeholder: "Select a customer"
});
$("#CustomerId").change(function () {
var param = $("#CustomerId Option:Selected").val();
$.ajax({
type: "POST",
url: '#Url.Action("GetCustDetails", "QuickInvoices")',
data: { Id: param },
dataType: "json"
contentType: 'application/json; charset=utf-8',
success: function(data) {
alert(data.msg);
},
error: function() {
alert("Error occured!!")
}
});
});
});

Finding it impossible to post simple ajax

I am realy struggling with this and would apprecate any advice.
I have this field
<input id="scanInput" type="text" placeholder="SCAN" class="form-control" />
For which I would like to make an ajax call when the field changes, so I tried
<script>
$("#scanInput").change(function () {
console.log('ye');
$.getJSON("?handler=GetPartDetails", function (data) {
//Do something with the data.
console.log('yay?');
}).fail(function (jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log("Request Failed: " + err);
});
});
</script>
Where my PageModel has this method
[HttpPost]
public IActionResult GetPartDetails()
{
return new JsonResult("hello");
}
and the url for the page in question is /packing/package/{id}
Now when I change the input value, I see ye on the console, and I can see that the network called http://localhost:7601/Packing/Package/40?handler=GetPartDetails (the correct URL I think?) with status code 200
But My breakpoint in GetPartDetails never hits, and I don't see yay? in the console.
I also see this message from the fail handler:
Request Failed: parsererror, SyntaxError: JSON.parse: unexpected character at line 3 column 1 of the JSON data
But I'm not even passing any JSON data... why must it do this
I also tried this way :
$.ajax({
type: "POST",
url: "?handler=GetPartDetails",
contentType : "application/json",
dataType: "json"
})
but I get
XML Parsing Error: no element found
Location: http://localhost:7601/Packing/Package/40?handler=GetPartDetails
Line Number 1, Column 1:
I also tried
$.ajax({
url: '/?handler=Filter',
data: {
data: "input"
},
error: function (ts) { alert(ts.responseText) }
})
.done(function (result) {
console.log('done')
}).fail(function (data) {
console.log('fail')
});
with Action
public JsonResult OnGetFilter(string data)
{
return new JsonResult("result");
}
but here I see the result text in the console but my breakpoint never hits the action and there are no network errors..............
What am I doing wrong?
Excuse me for posting this answer, I'd rather do this in the comment section, but I don't have the privilege yet.
Shouldn't your PageModel look like this ?
[HttpPost]
public IActionResult GetPartDetails() {
return new JsonResult {
Text = "text", Value = "value"
};
}
Somehow I found a setup that works but I have no idea why..
PageModel
[HttpGet]
public IActionResult OnGetPart(string input)
{
var bellNumber = input.Split('_')[1];
var partDetail = _context.Parts.FirstOrDefault(p => p.BellNumber == bellNumber);
return new JsonResult(partDetail);
}
Razor Page
$.ajax({
type: 'GET',
url: "/Packing/Package/" + #Model.Package.Id,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
input: barcode,
handler: 'Part'
},
success: function (datas) {
console.log('success');
$('#partDescription').html(datas.description);
}
});
For this issue, it is related with the Razor page handler. For default handler routing.
Handler methods for HTTP verbs ("unnamed" handler methods) follow a
convention: On[Async] (appending Async is optional but
recommended for async methods).
For your original post, to make it work with steps below:
Change GetPartDetails to OnGetPartDetails which handler is PartDetails and http verb is Get.
Remove [HttpPost] which already define the Get verb by OnGet.
Client Request
#section Scripts{
<script type="text/javascript">
$(document).ready(function(){
$("#scanInput").change(function () {
console.log('ye');
$.getJSON("?handler=PartDetails", function (data) {
//Do something with the data.
console.log('yay?');
}).fail(function (jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log("Request Failed: " + err);
});
});
});
</script>
}
You also could custom above rule by follow the above link to replace the default page app model provider

Always error funtion is executing in json ajax in asp.net controller

Java Script:-
function themechange(themeValue) {
$('#themeId').attr('href', '/zcv/resources/css' + '/' + 'theme-' + themeValue.toLowerCase() + '.css');
$.ajax({
url: '#Url.Action("ChangeTheme", "Login")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'themeValue': themeValue },
success: function (data) {
alert(data);
},
error: function () {
alert('Error occured');
}
});
}
In LoginContoller.cs:-
[HttpGet]
public JsonResult ChangeTheme(string themeValue)
{
System.Diagnostics.Debug.WriteLine("======ChangeTheme======");
Session["theme"] = themeValue;
String x= "========";
return Json(x, JsonRequestBehavior.AllowGet);
}
All the suggestion which replied so far are not working. Please give a executable project codes links for ASP.NET MVC Application which applies simple ajax with json for just calling a controller method.
You forget to assign the themeValue which get from HTML page by $('#themeId') also there is a problem you use GET instead of POST.
Try this
function themechange(themeValue) {
var themeValue = $('#themeId').attr('href', '/zcv/resources/css' + '/' + 'theme-' + themeValue.toLowerCase() + '.css');
$.ajax({
url: '#Url.Action("ChangeTheme", "Login")',
type: 'POST',
dataType: 'json',
cache: false,
data: { 'themeValue': themeValue },
success: function (data) {
alert(data);
},
error: function () {
alert('Error occured');
}
});
}
[HttpPost]
public JsonResult ChangeTheme(string themeValue)
{
System.Diagnostics.Debug.WriteLine("======ChangeTheme======");
Session["theme"] = themeValue;
String x= "========";
return Json(x, JsonRequestBehavior.AllowGet);
}

Autocomplete with Ajax returns No HTTP resource was found that matches the request URI

I am trying to implement an autocomplete on my textbox with data that comes from a web method. The webmethod works on the browser like:
http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers?SearchString=e
and these are the results:
[{"IssuerID":1,"Name":"test tester","ChequeAccountNumber":"12345678","CurrencyCode":"EUR"}]
Now, I am trying to add on the textbox the Name data from the response but I'm getting an error in the function below:
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers?{ 'SearchString': 'e'}'.","MessageDetail":"No action was found on the controller 'ModuleTask' that matches the request."}
Below, my AJAX call seems to fail for a reason, which I believe comes from passing wrongly the parameters. I do not have experience with ajax so far, so your input will be great.
<script type="text/javascript">
$(function () {
$("[id$=TextBox1]").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers")%>',
data: "{ 'SearchString': '" + request.term + "'}",
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("[id$=hfIssuerID]").val(i.item.val);
},
minLength: 1
});
});
</script>
My web method:
public class ModuleTaskController : DnnApiController
{
[AllowAnonymous()]
[HttpGet()]
public HttpResponseMessage GetIssuers(string SearchString)
{
try {
List<Issuers> listIssuers = new List<Issuers>();
IssuersController ic = new IssuersController();
listIssuers = ic.GetIssuers(10, SearchString);
return Request.CreateResponse(HttpStatusCode.OK, listIssuers.ToJson);
} catch (Exception exc) {
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc);
}
}
}
Any ideas?
EDIT:
$(function () {
$("[id$=TextBox1]").autocomplete({
source: function (request, response) {
var qstring = '?' + jQuery.param({ 'SearchString': request.term });
$.ajax({
url: '<%=ResolveUrl("http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers")%>' + qstring,
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("[id$=hfIssuerID]").val(i.item.val);
},
minLength: 1
});
});
Your web method is a GET and accepts a querystring yet your Ajax call is trying to pass a JSON object, which is getting appended to the end of your url. You can see this by reading what the URL actually is, in the error message
There are a bunch of different things you can do. This is just one.
// turn your search object into querystring
var qstring = '?'+ jQuery.param({ 'SearchString': request.term});
// append this querystring to the end of your url
$.ajax({
url: '<%=ResolveUrl("http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers")%>' + qstring ,
// remove data and datatype
type: "GET",
//... etc
Also in this case, it doesn't look like you need the ResolveUrl.
Perhaps try your URL as:
url:'http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers' + qstring;

Redirect with Ajax POST

i'm new with ajax and i'm trying to call a post action from an ajax method like that
$(".buttonSelection").click(function () {
selectedId = $(this).parents('tr:first').children('td:first').children('input:first').attr('value');
$.ajax({
// Call MaSelection action method
url: "/DemandeLocation/MaSelectionOffre",
data: { id: selectedId },
type: 'Post',
success: function (msg) {
window.location.replace('#Url.Content("~/DemandeLocation/MaSelectionOffre")');
},
error: function (xhr) {
alert("something seems wrong");
}
});
});
my post method goes with success but instead of redirectin me to the MaSelection View it return the first view where i call the method, so i tried to put a "Success" fragment in my ajax method and i puted a location replace by "Ma selection" view but i know that the view lose the id so it become null, how can i do it with Ajax,
here my post action for more details
[HttpPost]
[Authorize(Roles = "Locataire")]
public ActionResult MaSelectionOffre(string id)
{
int DemandeLocationGetbyId = Convert.ToInt32(id);
var selectionOffre = db.SelectionOffreLocationSet.Where(model => model.DemandeLocationPublication_ID == DemandeLocationGetbyId).ToList();
return View("MaSelectionOffre", selectionOffre);
}
use json as datatype;
$(".buttonSelection").click(function () {
selectedId = $(this).parents('tr:first').children('td:first').children('input:first').attr('value');
$.ajax({
// Call MaSelection action method
url: "/DemandeLocation/MaSelectionOffre",
dataType:"json",
data: { id: selectedId },
type: 'Post',
success: function (msg) {
window.location.href = msg.redirect;
},
error: function (xhr) {
alert("something seems wrong");
}
});
});
also you need this ;
Convert object to JSON string in C#
If you want redirect page, after ajax call you should use
...
success: function (msg) {
window.location.href = '#Url.Action("MaSelectionOffre", "DemandeLocation")';
},
...
EDIT
If you want replace result, use something like following:
HTML
<div id="updateTargetId">
//table
//tr
//td
//your button that has cssClass buttonSelection
</div>
JS
$(".buttonSelection").click(function () {
selectedId = $(this).parents('tr:first').children('td:first').children('input:first').attr('value');
$.ajax({
// Call MaSelection action method
url: "/DemandeLocation/MaSelectionOffre",
dataType:"json",
data: { id: selectedId },
type: 'Post',
success: function (msg) {
$("#updateTargetId").html(msg);
},
error: function (xhr) {
alert("something seems wrong");
}
});
});
CONTROLLER (return PartialView)
[HttpPost]
[Authorize(Roles = "Locataire")]
public ActionResult MaSelectionOffre(string id)
{
int DemandeLocationGetbyId = Convert.ToInt32(id);
var selectionOffre = db.SelectionOffreLocationSet.Where(model => model.DemandeLocationPublication_ID == DemandeLocationGetbyId).ToList();
return PartialView("MaSelectionOffre", selectionOffre);
}
i changed my action to a get action and in my button i just added window.location.replace with link and ID
<button type="button" class="buttonSelection" onclick="window.location.replace('#Url.Content("~/DemandeLocation/MaSelectionOffre?id="+item.Publication_ID)')"> <span class="ui-icon ui-icon-cart"></span> </button>

Categories

Resources