MVC Get method not hit after javascript ajax post - javascript

So I have these two controller methods that works:
[HttpGet]
public ActionResult EditWork(string work)
{
// do the bla bla
return Json(new {Success = true});
}
[HttpPost]
public ActionResult EditWork(WorkObjet work)
{
// Do the bla bla!
var listWork = TempData.Peek("myWorks") as List<WorkObjet>;
// Edit the value of the correct work object.
return Json(new {Success = true});
}
And they get called via Javascript like this:
function EditWork(event, anc) {
event.preventDefault();
var param = anc.attributes["data-id"].nodeValue;
$.ajax({
type: 'GET',
url: #Url.Action("EditWork", "Work"),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: { work: param }
}).done(function (data) {
if (data.Success === true) {
// Update the fields
} else {
console.log("Error:" + param);
}
}).fail(function (xhr) {
console.log(xhr.responseText);
});
}
function SaveEdit(){
var myWork = GetMyWork() // calls the field via jQuery
$.ajax({
type: 'POST',
url: #Url.Action("EditWork", "Work"),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ work: myWork })
}).done(function (data) {
if (data.Success === true) {
// reload the page?
windows.location.reload();
} else {
console.log("Error:" + param);
}
}).fail(function (xhr) {
console.log(xhr.responseText);
});
}
And they work really well. So let's do the following:
Click on the button to edit a work
The Controller Get method EditWork is hit via breakpoint;
Edit the work, then save
The Controller Post method EditWork is hit via breakpoint and the work is updated in a list;
The page gets refreshed
Click on the button to edit again
The GET method is not hit via breakpoint, The old work gets shown at screen. Very odd.
Edit the work, then save
The POST method is hit with the values...
How is step seven even possible?

Add this to your GET request:
cache: false
By default jQuery allows browser to cache the result of GET Ajax requests. Look at the documentation for more info.

Related

I keep getting 415 error while post json data to asp.net controller

I am trying to develop simple jouneral voucher form.
var Things=[];
function addNewEntry() {
var thing = {
//Id: parseInt($('#Id').val()),
AcNumber: $('#AcNumber').val(),
TranAmount: parseInt($('#TranAmount').val()),
TranType: $('#TranType').val(),
Tdate: $('#Tdate').val(),
};
things.push(thing);
return things;
}
function clickPostBtn() {
$('#post').click(function (ev) {
console.log('post botton work started');
ev.preventDefault();
addNewEntry();
//debit credit validation
var myJsonString = JSON.stringify(things);
$.ajax({
contentType: 'application/Json; charset=UTF-8',
dataType: 'json',
type: 'POST',
url: '/Transaction/DoubleEntry',
data: myJsonString,
success: function () {
alert('success');
},
failure: function (response) {
$('#result').html(response);
}
});
document.getElementById('myform').submit();
my controller looks like below
public IActionResult doubleentry([FromBody] IEnumerable<TransactionTbl> trans)
{
//do something with incoming data
return RedirectToAction("dummyview", "Transaction");
}
whenever i click post button, data do get my controller but throw 415 after that,
i have tried with in ajax
application/x-www.formencoded
multipart/formdata
with and without binding attribute in controller.

Is it impossible to download file via AJAX call in ASP.NET MVC5?

I know it seems to be better to use normal call instead of AJAX call but for some reason i.e. displaying error message on modal dialog in case a problem during download, I need to download file by using an AJAX call in an MVC5 project. Here is what I did finally after lot of tries:
View:
Download
function downloadFile() {
$.ajax({
type: 'POST',
url: '/Experiment/GetFile',
data: '{id:' + 8 + '}', //For test purpose I used static id
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (returnValue) {
window.location = '/Experiment/GetFile?id=' + returnValue;
}
});
};
Controller:
In Controller, I have a method something like that, but I am really confused if I should do the same method for AJAX Post and success method or not.
[HttpPost]
public ActionResult GetFile(int id)
{
var dataContext = repository.FileAttachments.FirstOrDefault(m => m.Id == id);
if (dataContext == null)
{
return Json(new { success = true, returnValue = "8" });
}
else
{
return Json(new { success = false, message= "Error..." }, JsonRequestBehavior.AllowGet);
}
}
Is there a smart approach to perform this dosnload operation using AJAX call in ASP.NET MVC5?
You need to return file name or file path
Example "/file/download.doc"
And then you need to edit view page like follow
Download
<a href="" id="todownload" download>
function downloadFile() {
$.ajax({ type: 'POST', url: '/Experiment/GetFile', data: '{id:' + 8 + '}', //For test purpose I used static id
contentType: 'application/json; charset=utf-8', dataType: 'json',
success: function (returnValue)
$("#todownload").attr('href',returnValue);
$("#todownload").click();
}
});
};

Web service receiving null with jQuery post JSON

The web service on http://localhost:57501/api/addDatabase has the following code.
[System.Web.Mvc.HttpPost]
public ActionResult Post(addDatabase pNuevaConeccion)
{
pNuevaConeccion.insertarMetaData();
return null;
}
The Ajax function is on a javascript that creates the JSON from the give values on http://localhost:1161/CreateServer.
$(document).ready(function ()
{
$("#createServer").click(function (e) {
e.preventDefault(); //Prevent the normal submission action
var frm = $("#CreateServerID");
var dataa = JSON.stringify(frm.serializeJSON());
console.log(dataa);
$.ajax({
type: 'POST',
url: 'http://localhost:57501/api/addDatabase/',
contentType: 'application/json; charset=utf-8',
crossDomain: true,
//ContentLength: dataa.length,
data: dataa,
datatype: 'json',
error: function (response)
{
alert(response.responseText);
},
success: function (response)
{
alert(response);
if (response == "Database successfully connected") {
var pagina = "/CreateServer"
location.href = pagina
}
}
});
});
});
When I run this code an alert pops up saying "undefined" but if I delete the contentType the alert doesn't show up. The problem is that the variables that the function Post (from the web service) receives are NULL even though I know that the JSON named dataa is not NULL since I did a console.log.
I have seen various examples and pretty much all of them say that I should use a relative URL but the problem is that since there are 2 different domains and when I tried it, it couldn't find the URL since it's not in the same localhost.
Web service should return a JSON format instead of null. like below example.
public JsonResult Post()
{
string output = pNuevaConeccion.insertarMetaData();
return Json(output, JsonRequestBehavior.AllowGet);
}
try to use this code for calling the web method
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: dataa,
url: 'http://localhost:57501/api/addDatabase/',
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
its my old code.(ensure action parameter variable name and post variable name are same)
$('#ConnectionAddres_ZonesId').change(function () {
var optionSelected = $(this).find("option:selected");
var id = { id: optionSelected.val() };
$.ajax({
type: "POST",
url: '#Url.Action("GetParetArea", "Customers")',
contentType: "application/json;charset=utf-8",
data: JSON.stringify(id),
dataType: "json",
success: function (data) {
$('#ConnectionAddres_ParentAreaId').empty().append('<option value="">Select parent area</option>');
$.each(data, function (index, value) {
$('#ConnectionAddres_ParentAreaId').append($('<option />', {
value: value.Id,
text: value.Area
}));
});
},
});
});
public ActionResult GetParetArea(int id)
{
var parents="";
return Json(parents, JsonRequestBehavior.AllowGet);
}

MVC jQuery Ajax Post - can only get it to work with hard-coded values

So I have a basic controller accepting a post..
[HttpPost]
public ActionResult Submit(string postCost)
{
//Do stuff here before sending back redirect details...
return Json(new { result = "Redirect", url = Url.Action("Index", "Confirm") });
}
And I'm posting via jquery ajax method:
$.ajax({
url: partyURL,
dataType: 'json',
contentType: 'application/json', //charset=utf-8',
type: 'POST',
data: { postCost: postageCost}, //**This fails!**
//data: "{'postCost':'3.50'}", //**This works**
success: function (response) {
if (response.result == 'SoldOut') {
$("#soldOut").show();
}
else if (response.result == 'Redirect') {
//All good, onward to confirmation page
window.location = response.url;
}
},
error: function (xhr, status, error) {
// Error handling here
}
});
where the postageCost variable sent in when it fails returning status 500:
postageCost = '3.50';
postageCost = JSON.stringify(postageCost); //also fails with this
but if I hard-code the data definition as
data: "{'postCost':'3.50'}",
It works fine.
The key must therefore lie in what I'm doing with the data element?
you need to do
var datum = {'postCost': '3.50'};
data: JSON.stringify(datum), //Ajax call data

.NET Make second ajax call after success of first

I've got 2 ajax calls to go to 2 separate controller methods, one to create a floorplan object and save it to the database, the other sends an array of any plan objects (chairs, tables etc.) to the same database.
I have the second ajax call within the success of the first call, however it seems to not occur initially. I have set up breakpoints to check the data, and a floorplan is definitely added with valid data. If I attempt to create another, it works then, so I'm not sure if it is a database issue or if my JavaScript is wrong.
This is the ajax calls I have for my JavaScript save function
$.ajax({
url: "/Floorplans/Create",
type: "POST",
contentType: "application/json",
data: JSON.stringify($floorplan),
success: function () {
$.ajax({
url: "/planObjects/Create",
type: "POST",
contentType: "application/json",
data: JSON.stringify($objArray)
//objArray is an array of planObjects
});
}
});
My floorplan controller:
[HttpPost]
//Floorplan controller
public ActionResult Create(Floorplan floorplan)
{
if (ModelState.IsValid){
db.Floorplans.Add(floorplan);
db.SaveChanges();
return Json(new {success = true});
}
else{
return Json(new {success = false});
}
}
planObjects controller:
[HttpPost]
public void Create(List<planObject> newObjects)
{
var model = new planObject();
if (ModelState.IsValid)
{
newObjects.ForEach(r => db.planObjects.Add(r));
db.SaveChanges();
}
}
With this code, the ajax call within the success of the first ajax call is not executed on first attempt, but if I make another floorplan it works perfectly. Can you guys see a fix to the problem? I was attempting to use a single controller action method but I was unable to get it working correctly.
Modified your code a bit (I could make it work locally). I suspect it could be the "data" element in second call causing the trouble. I would check the progress step by step and go from there.
If you add some alert or log messages like below, what do you see?
<script>
$.ajax({
url: '#Url.Action("Create", "FloorPlans")',
type: "POST",
contentType: "application/json",
data: JSON.stringify($floorplan),
success: function(result) {
if (result.success) {
Log("Floor plan created successfully, adding plan objects...");
$.ajax({
url: '#Url.Action("Create", "PlanObjects")',
type: "POST",
contentType: "application/json",
data: JSON.stringify($objArray),
//objArray is an array of planObjects
success: function(result2) {
if (result2.success) {
Log("Plan objects created successfully");
} else {
Log("Failed to create plan objects");
}
}
});
} else {
Log("Failed to add floor plan");
}
}
});
function Log(data) {
//alert(data);
console.log(data);
}
</script>

Categories

Resources