ASP.Net MVC 3 Ajax query not firing - c#

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.

Related

Why does my ajax call not returning my data from controller?

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.

No errors on backend, but Ajax function is failing

I have an Ajax Call and a Controller with some methods and there is something weird.
The Ajax call can reach the Controller Method. The method is returning the value perfectly, no errors, nothing. However, in the AJAX the return is coming with error (not on success of Ajax).
Moreover, If I inspect the return I can see the correct values on responseJson, but the status is 404 and statusText is "error" ({"readyState":4,"status":404,"statusText":"error"})
Anyone have an idea what is going on? There is no error in backend, however error in Ajax.
Controller Method
public JsonResult SceneListUpdated(string sceneId)
{
SceneListModel model = new SceneListModel();
var licenseValidationState = KeygenLicenseState.CheckLicense();
if (licenseValidationState == 0)
{
SceneListService sceneService = new SceneListService();
model = sceneService.GetSceneListUpdated(sceneId);
return Json(new { Success = true, data = model }, JsonRequestBehavior.AllowGet );
}
return Json(new { Success = false, data = "" }, JsonRequestBehavior.AllowGet);
}
Ajax Function
$.ajax({
url: "/api/test/SceneList/SceneListUpdated?sceneId=" + sceneIdAux, //Method in controller
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (e) {
},
error: function (data) {
}
});
try to fix the ajax
$.ajax({
url: "/api/test/SceneList/SceneListUpdated/"+ sceneIdAux, //Method in controller
type: "GET",
success: function (e) {
},
error: function (data) {
}
});
and maybe you can try one of these routing since you have 404
[Route("{sceneId}")]
[Route("~/api/SceneList/SceneListUpdated/{sceneId}")]
public JsonResult SceneListUpdated(string sceneId)

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

Ajax Post method not working for user defined function

UpdateModule is a function used for update module details. It's not a view page.
When click on update, it returns 500 (internal server error) or 404 error
please help to fix it
$.ajax({
type: 'POST',
url: '#Url.Action("ETM_PRODUCTS","UpdateModule")',
//contentType: 'application/json',
datatype: JSON,
data: { 'ModuleID': ModuleID, 'ModuleName': ModuleName, 'ModuleDescription': ModuleDescription },
success: function (data) {
if (data == true) {
alert("Updated Successfully");
}
},
error: function (msg) {
alert("Error")
},
});
c#
public JsonResult UpdateModule(int ModuleID,string ModuleName,string ModuleDescription) {
bool status = true;
PROD_MODULE tabledata = db.PROD_MODULE.Where(x => x.ETM_MODULE_ID == ModuleID)
.FirstOrDefault();
tabledata.NAME = ModuleName;
tabledata.DESCRIPTION = ModuleDescription;
db.SaveChanges();
return Json ( status, JsonRequestBehavior.AllowGet );
}
There is a problem in the way you call Url.Action.
The first parameter is the action and the second the controller.
Here is the documentation : link

Formcollection input values are empty in controller after ajax call

I faced a problem with IE and FF; my application is working with Google Chrome.
I am binding a model to a view in ASP.NET MVC
I have a table row inside a form(and some other controls). I replace the table row's content on a button click with ajax call. After ajax call, if I submit form as shown below, I can not get formcollection inputs from controller method. There is no problem when I submit form before ajax call.
The js code to update table row's content:
function reloadCriteriaTable(unitID, criteriaCode, icerikRowSpan, icerikOnay) {
$.ajax({
type: "GET",
url: 'ApproveParts/ReloadCriteria',
data: { contentID: $('[name="contentID"]').val(), unitID: unitID, criteriaCode: criteriaCode, selectedValue: $("#validator_" + criteriaCode).val(), icerikRowSpan: icerikRowSpan, icerikOnay: icerikOnay },
cache: false,
type: "POST",
success: function (data, textStatus, XMLHttpRequest) {
$('#tr_' + criteriaCode).replaceWith(data);
$('#continueBtn').on('click', function () {
$('#form_3').submit();
return false;
});
},
error: function (xhr, status, error) {
alert(xhr + ' ' + status + " : " + error);
}
});
}
Onclick function:
$(document).on("click", ".btnSubmitCriteria", function () {
$('#form_3').submit();
return false;
});
Controller method:
[HttpPost]
public ActionResult CourseCriteriaApprovment(FormCollection collection)
{
}
To begin with why you have mentioned both type "GET" and "POST" in your ajax call. Use "POST" only.
Try this
$.ajax({
type: 'POST',
url: '/ApproveParts/ReloadCriteria',
dataType: 'json',
contentType: 'application/json',
data : return JSON.stringify({
contentID: $('[name="contentID"]').val(),
unitID: unitID,
criteriaCode: criteriaCode,
selectedValue: $("#validator_" + criteriaCode).val(),
icerikRowSpan: icerikRowSpan,
icerikOnay: icerikOnay
});
});
In your controller action accept a class instead of FormCollection. Where the class has all properties defined same as the ones you are sending in your ajax call.

Categories

Resources