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
Related
In my application I have a drop-down menu that lists various customers, and a second drop-down that will list the cities with which a given customer is associated. Selecting a customer should populate the second drop-down with the relevant list of locations. This happens by triggering an Ajax call to a method in the controller, which passes the name of the selected customer in variable "loc". The list of locations is obtained via an EF Core query.
This all works as expected on my local machine, but when running on our server it returns a 404 - Not Found error.
The Ajax call looks like this:
$.ajax({
url: "/[Controller]/GetLocations",
type: "POST",
dataType: "text",
data: { 'loc': loc },
success: function (data, textStatus, jqXHR) {
var listData = JSON.parse(data);
resetLocationList();
for (var listSize = 0; listSize < listData.length; listSize++) {
$('#ffBankLocation').append('<option value="' + listData[listSize] + '">' +
listData[listSize] + '</option>');
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('Error caught: ');
console.log(errorThrown);
}
});
And the method in the controller looks like this:
[HttpPost]
public async Task<JsonResult> GetLocations(string loc)
{
var locations = await _repo.GetLocationsByName(loc);
return Json(locations);
}
Finally, the URL as reported in the 404 error looks like this:
https://[URL]/[Controller]/GetLocations?loc=Some%20Location
Given that the URL value isn't being found, I doubt the settings after that have anything to do with the problem. The only thing I could think to change there is that the controller was contained in a sub-folder within the Controllers folder (Controllers/myFolder/Controller), but moving the controller to the main Controllers folder, no sub-folder in between, doesn't resolve the issue.
Any advice appreciated.
EDIT: To be clear about moving the controller, I did not move it from the main Controllers folder, I only moved it out of the sub-directory within the Controllers folder in which it was previously found.
try to remove [HttpPost], and add attribute route
[Route("~/mycontroller/GetLocations")]
public async Task<JsonResult> GetLocations(string loc)
if it is still not working try to change ajax to get
$.ajax({
url: "/[Controller]/GetLocations?loc="+loc,
type: "GET",
dataType: "json",
success: function (data, textStatus, jqXHR) {
and never ever move controllers from default Controllers folder
Problem solved. I needed to convert my drop-down list into an #Html.DropDownListFor object, and wrap it in a form object like so:
<form id="custNameForm" asp-controller="myController" asp-action="GetLocations" method="post">
#Html.AntiForgeryToken()
#Html.DropDownListFor(x => x.Name, new SelectList((List<string>)ViewBag.custList), "Select Customer",
new { #class="form-control text-center" })
</form>
Next, in my javascript file, I add the following "change" listener:
.on('change', '#CustName', function (e) {
e.preventDefault();
GetLocations(e);
})
...which points to this jquery function:
function GetLocations(e) {
var loc = $('#CustName option:selected').val();
var noLoc = loc === '' || loc === 'Select Customer';
if (!noLoc) {
var form = $('#custNameForm');
var url = form.attr('action');
var token = $('input[name="__RequestVerificationToken"]').val();
$.ajax({
url: url,
type: "POST",
dataType: "json",
data: {
__RequestVerificationToken: token,
'loc': loc
},
success: function (data, textStatus, jqXHR) {
var listData = data;
resetLocationList();
for (var listSize = 0; listSize < listData.length; listSize++) {
$('#custLocation').append('<option value="' + listData[listSize] + '">' + listData[listSize] + '</option>');
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('Error caught: ');
console.log(errorThrown);
}
});
}
else {
parseXML('');
}
$('#custLocation').prop('disabled', noLoc);
}
... where "#custLocation is the ID of the dropdown to be populated with the list of customer locations.
I'm having a hard time getting the data from client but my code on visual studio when I'm on a breakpoint it gets the data but I cant receive it on my browser.
Here's my AJAX call
function GetRecord() {
var elemEmployee = 55;
var startDT = $('#searchFilterStartDate').val();
var endDT = $('#searchFilterEndDate').val();
$.ajax({
url: "/Modules/GetDTRRecord",
type: "GET",
data: {
EmployeeID: elemEmployee,
DateFrom: endDT,
DateTo: startDT,
},
dataType: "json",
success: function(data) {
console.log('Data Success ');
console.log(data);
}
});
}
here's my controller:
[HttpGet]
public List<DTRRecordList.Entity> GetDTRRecord(DTRRecordList.Entity data)
{
var entity = new DTRRecordList();
return entity.GetDTR(data);
}
As you can see below I got 38 records but I can't receive it on my js even that console.log('Data Success') is not shown on my console.
You need to return JSON from your Controller method. You can change your method to:
[HttpGet]
public JsonResult GetDTRRecord(DTRRecordList.Entity data)
{
var entity = new DTRRecordList();
var getDTR= entity.GetDTR(data);
return Json(new {dtrData= getDTR});
}
And in your Ajax call:
$.ajax({
url: "/Modules/GetDTRRecord",
type: "GET",
data: {
EmployeeID: elemEmployee,
DateFrom: endDT,
DateTo: startDT,
},
dataType: "json",
success: function(data) {
console.log('Data Success ');
console.log(data.dtrData);
},
error: function(error) {
console.log(error)
}
});
After a discussion with O.P and seeing the code, it was found that the issue was happening because the form submit was happening which was causing the page to reload twice. After removing the form event and adding the click event in:
$(document).ready(function () {
//On Clink "Search Button"
$("#searchbtn").click(
function () { GetRecord(); });
});
The data seems to be coming as expected.
Hi I'm new to umbraco MVC. I'm using version 7. What I'm trying to do is following:
An External page www.ble1.com is posting to my page www.le2.com/recieve when that happens ble1 is posting to the page and in the browser dev tools I can see the Form Data name of the parameter (tok) and some encoded string.
Now I want to take this data and send it to the controller code behind the macro running on my page www.le2.com/recieve. How would this be possible? I'm used to workin in asp.NET where I have the pageLoad function in code behind but I'm confused how to tackle this in Umbraco MVC.
What I have done so far is Create cshtml:
#inherits Umbraco.Web.Macros.PartialViewMacroPage
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '../../../umbraco/surface/land/Login',
data: JSON.stringify({}),
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (data) {
alert(data.d);
}
});
});
</script>
My Controller
public JsonResult Login()
{
//Don't know what to do here!!!!
//Everything that I have tryed has failed. Calling Request....etc.
}
I have never worked with Umbraco, but I have with MVC.
You Login method is not marked to receive POST requests. You need to use the attribute [HttpPost]
Your Login method does not have any Arguments, so, even if you fix your issue #1, it will not get any data.
So, first, you need some data in your Action Method, so you either need a ViewModel or a set or parameters, this is a ViewModel sample:
public class MyLoginViewModel
{
public string UserName { get; set; }
public string Password { get; set; }
}
Now we use that ViewModel in the Action Method:
[HttpPost]
public JsonResult Login(MyLoginViewModel model)
{
if (ModelState.IsValid)
{
// Do something here (probably use Umbraco internal's authorization layer)
var valid = (model.UserName == "user" && model.Password == "pwd");
if (valid)
return Json(new { code = 0, message = "OK" });
else
return Json(new { code = 10, message = "User/Password does not match" });
}
// Model is invalid, report error
return Json(new { code = -1, message = "invalid arguments" });
}
It is a very naive example, it makes sure the ViewModel is Valid, if it is, it performs the actual login logic, in this sample is just checks 2 values and returns the status.
In the HTML page, you could have:
<input type="text" id="userName" />
<input type="text" id="password" />
<button id="login">Login</button>
<script>
$(document).ready(function () {
$("#login").click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/home/Login',
data: JSON.stringify({ UserName: $('#userName').val(), Password: $('#password').val() }),
dataType: 'json',
success: function (data) {
alert(data.message);
},
error: function (data) {
alert("An error has occurred while processing your request");
}
});
})
});
</script>
Again, very a naive example.
I hope it gives you enough information to adapt it to Umbraco.
Sorry I cannot give you Umbraco specific information.
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")',
/* ... */
});
I have a very simple ajax call to refresh some data on my webpage, but it doesn't seem to fire correctly. The data that the call brings back is the same everytime even if the underlying data changes.
The ajax call looks like this:
function RefreshContent() {
//create the link
var link = "/Address/ListByAjax/" + $('#Id').val();
$.ajax({
type: "GET",
url: link,
success: function (data) {
$("#Address").html(data);
},
error: function (req, status, error) {
alert('an error occured: ' + error);
}
});
}
My controller looks like this:
public ActionResult ListByAjax(int Id)
{
var list = db.Address.Where(i => i.Person_Id == Id);
return PartialView("_List", list.ToList());
}
Try setting the cache to false in your ajax call - that will force the browser to send the request through to the controller:
function RefreshContent() {
//create the link
var link = "/Address/ListByAjax/" + $('#Id').val();
$.ajax({
type: "GET",
url: link,
cache: false,
success: function (data) {
$("#Address").html(data);
},
error: function (req, status, error) {
alert('an error occured: ' + error);
}
});
}
Use
ajaxSetup({ cache: false }); });
This turns off caching for all ajax calls made by your app.