I have an issue with a simple jQuery $.post in my application. I have tried many methods and solutions on the internet to no avail. When post request is sent I see 400 error
public class RecoveryAdhocInvoicingModel : PageModel
{
Public IActionResult OnPostDoJob(string invNo, string account)
{
//var emailAddress = Request.Form["emailaddress"];
// do something with emailAddress
return new JsonResult("");
}
}
In my script the $.post method is called via button click:
$('#submitBtnUpdateJob').click(function (evt) {
var formdata = new FormData();
formdata.append("invNo", $('#adhocInvoiceNumber').val());
formdata.append("account", $('#invoiceAccountInput').val());
$.post(window.location.href + '?handler=DoJob', JSON.stringify(formdata), function () {
alert('Posted');
});
});
Solution folder path
You need to add the RequestVerificationToken header to the request.
$.ajax({
type: "POST",
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
url: window.location.href + '?handler=DoJob',
data: {
"invNo": $('#adhocInvoiceNumber').val(),
"account": $('#invoiceAccountInput').val()
},
contentType: "application/x-www-form-urlencoded"
}).done(function (response) {
alert('Posted');
});
Documentation: https://www.learnrazorpages.com/security/request-verification#ajax-post-requests-and-json
Related
I'm trying to implement file download functionality thru ajax call in MVC.
After calling of controller method i always have a "parseerror", can somebody explain me why?
my ajax:
tab.on("click", ".FileDownload", function (e) {
//$('#uploadStatus').html("ok");
var tr = $(this).closest("tr");
var id = tr.data("id");
$.ajax({
type: "POST",
url: "/File/FileDownload",
//contentType: false,
//processData: false,
//dataType: "json",
data: { fileId: id },
success: function (data) {
$('#uploadStatus').html("ok");
},
error: function (err) {
alert(err.statusText);
}
});
});
and controller:
[HttpPost]
public FileResult FileDownload(int? fileId)
{
FileDBEntities db = new FileDBEntities();
tblFile file = db.tblFiles.ToList().Find(p => p.id == fileId.Value);
return File(file.Data, file.ContentType, file.Name);
}
with simple download link in razor it works, but not with ajax.
What am I doing wrong here?
Why not simple use
tab.on("click", ".FileDownload", function (e) {
//$('#uploadStatus').html("ok");
var tr = $(this).closest("tr");
var id = tr.data("id");
window.location = window.location.origin + '/File/FileDownload?fileId=' + id;
});
[HttpGet]
public FileResult FileDownload(int? fileId)
I am passing values to the action method using the ajax call. My action method name is TagTargets and this method has three parameters. I am also giving the exact path also but getting the error The resource cannot be found.
//Ajax Call to get targets Data
function TargetsData() {
var realTags = $('#Raw_Tag_List').val();
var calculatedTags = $('#Calculated_Tag_List').val();
var manulTags = $('#Manual_Tag_List').val();
$.ajax({
url: 'TagTargets',
type: 'Post',
contentType: 'application/json',
dataType: 'json',
data: { 'RealTags': realTags, 'CalculatedTags': calculatedTags, 'ManulTags':manulTags},
success: function (data) {
if (data.success) {
alert('Ok')
}
else {
alert('Not ok');
}
}
});
debugger;
}
//Action Method
[HttpPost]
public JsonResult TagTargets(List<string> RealTags, List<string> CalculatedTags, List<string> ManulTags)
{
return Json(true);
}
change your url to a valid url.
url: "#Url.Action("TagTargets","ControllerName");",
I'm trying to post a single object data to an MVC Controler using JQuery, Below are my codes.
//declare of type Object of GroupData
var GroupData = {};
//pass each data into the object
GroupData.groupName = $('#groupName').val();
GroupData.narration = $('#narration').val();
GroupData.investmentCode = $('#investmentCode').val();
GroupData.isNew = isNewItem;
//send to server
$.ajax({
url: "/Admin/SaveContributionInvestGroup",
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify({ GroupData: JSON.stringify(GroupData) }),
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
Below is my controller.
[HttpPost]
public JsonResult SaveContributionInvestGroup(ContributionInvestmentGroup GroupData)
{
ClsResponse response = new ClsResponse();
ClsContributionInvestmentGroup clsClsContributionInvestmentGroup = new ClsContributionInvestmentGroup();
var userID = (int)Session["userID"];
var sessionID = (Session["sessionID"]).ToString();
if (contributionGroupData != null)
{
//get the data from the cient that was passed
ContributionInvestmentGroup objData = new ContributionInvestmentGroup()
{
contributionInvestmentGroupID = 0,
groupName = GroupData.groupName,
narration = GroupData.narration,
investmentCode = GroupData.investmentCode,
isNew = GroupData.isNew
};
response = clsClsContributionInvestmentGroup.initiateNewContributionInvestmentGroup(sessionID, objData);
}
else
{
response.IsException = true;
response.IsSucess = false;
response.Message = "A system exception occurred kindly contact your Administrator.";
}
return Json(new
{
response.IsSucess,
response.Message
});
}
The issue is, the data is not been posted to the controller, the controller receives a null object.
Kindly assist, would really appreciate your effort, thanks.
Try Like this:
//send to server
$.ajax({
type: "POST",
url: "/Admin/SaveContributionInvestGroup",
dataType: "json",
data: GroupData,
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
in your controller your dont have custom binding to bind JSON to your model thats why you get null in you parameter.
instead just post it as query, try simply changes your ajax option like so:
{
...
contentType: "application/x-www-form-urlencoded", //default:
...,
data: $.param(GroupData),
...
}
and perhaps property names are case sensitive so you will need to change your javascript model's name
I'm making a website with web API, I tried to send JSON to my controller but this is the error I keep getting.
Multiple actions were found that match the request:
Post on type AuctionWebsiteASP.Controllers.MovesController
readDatabase on type AuctionWebsiteASP.Controllers.MovesController
newItem on type AuctionWebsiteASP.Controllers.MovesController
First I tried searching for a fix but none of the fixes here helped.
My Controller
public class MovesController : ApiController
{
[AcceptVerbs("GET", "POST")]
public HttpResponseMessage Post([FromBody] Product product)
{
products.Add(product);
newItem();
return Request.CreateResponse(HttpStatusCode.OK, product);
}
}
My JS
$.ajax({
type: "POST",
dataType: "json",
url: "/api/moves/",
data: source,
success: function (data) {
$("#nStart").val(null);
$("#nImg").val(null);
$("#nMaker").val(null);
$("#nModel").val(null);
$("#nSerial").val(null);
$("#nCpu").val(null);
$("#nRam").val(null);
$("#nGpu").val(null);
$("#nStorage").val(null);
$("#nBattery").val(null);
$("#nDrivers").val(null);
$("#nAccessories").val(null);
$("#nNotes").val(null);
console.log("Data has been sent!");
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
alert("ERROR!");
}
});
Thanks in advance!
Your route is probably like this
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
But in order to have multiple actions with the same http method you need to provide webapi with more information via the route like so:
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });
Try to use Route attribute to distinguish each action e.g
public class MovesController : ApiController
{
[Route("Product")]
public HttpResponseMessage Post([FromBody] Product product)
{
products.Add(product);
newItem();
return Request.CreateResponse(HttpStatusCode.OK, product);
}
}
$.ajax({
type: "POST",
dataType: "json",
url: "/api/moves/product",
data: source,
success: function (data) {
$("#nStart").val(null);
$("#nImg").val(null);
$("#nMaker").val(null);
$("#nModel").val(null);
$("#nSerial").val(null);
$("#nCpu").val(null);
$("#nRam").val(null);
$("#nGpu").val(null);
$("#nStorage").val(null);
$("#nBattery").val(null);
$("#nDrivers").val(null);
$("#nAccessories").val(null);
$("#nNotes").val(null);
console.log("Data has been sent!");
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
alert("ERROR!");
}
});
I'm attempting to pull the title from the metadata of a URL on the client side so it appears in real time (much like pasting a link on FB / Twitter). However I am struggling to load the url from an input and send the data to a function to make it read on console.log without having to submit the form yet.
Jade
form(method='post' action='/submit', class='plans', id='plans')
.form-group
label Do you have a link?
input.form-control(name='link', type='url', required='required', onchange='scrapeMetadata();', onkeyup='this.onchange();', onpaste='this.onchange();', oninput='this.onchange();')
JS
function scrapeMetadata(link) {
var url = link;
console.log(url)
};
Server-side, have the browser send the url via ajax and display that.
Like in this fiddle: https://jsfiddle.net/mo0qa8yk
function getTitle(url) {
try {
return new window.URL(url).host;
} catch(ex) {
console.error(ex);
return 'N/A';
}
}
window.scrapeMetadata = function () {
var url = $('#url').val();
$.ajax({
type: 'GET',
url: '//jsfiddle.net/echo/jsonp/',
data: {
url: url,
title: getTitle(url) //cheat , the server sould return {title:'...'}
},
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: show_response,
error: function(e) {
console.error(e.message);
}
});
};
show_response = function(obj) {
var result = $('#post');
result.html("");
result.append('<li>' + obj.title + '</li>')
};