I am using Ajax call to call a Controller method but I am getting this error:
http://localhost:55942/%22GetCalculateAmortizationSchedule%22,%20%22Home%22 404 (Not Found)
This is my Controller method:
[HttpPost]
public ActionResult GetCalculateAmortizationSchedule()
{
var data = ......
var httpClient = new HttpClient();
var response = httpClient.PostAsJsonAsync("http://localhost:62815/v1/APR/CalculateAmortizationSchedule", data).Result;
var returnValue = response.Content.ReadAsAsync<Dictionary<int, AmItem>>().Result;
return Content(returnValue.ToString());
}
This is the View code:
<form id="MyForm" method="post">
....
<input type="submit" id="test" value="test" />
</form>
and this is the Ajax code:
$('#MyForm').submit(function (e) {
$.ajax({
url: '#Url.Action("GetCalculateAmortizationSchedule", "Home")',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
contentType: false,
processData: false,
success: function (result) {
alert("success");
console.log(result.data);
// here in result you will get your data
},
error: function (result) {
}
});
e.preventDefault();
});
I think problem is this line that cannot find the url:
url: '#Url.Action("GetCalculateAmortizationSchedule", "Home")',
Use this instead of URl
url: "/home/GetCalculateAmortizationSchedule"
If you on same controller then do not need to add controller name
url: '#Url.Action("GetCalculateAmortizationSchedule")',
Related
I am trying to make an ajax call in .netcore 2.0. After doing some research online I have added the cshtml and the method below to my project. The current state of my application is that when I click the CreateNewTwitterData input "Hello world" is return as my new page (I have not written an java script as yet but this functionality was carried out is it the CSHTML that makes the post request?). I would like to keep the same page with the URL below and using some java-script to update the information on the current page.
Current URL:
http://localhost:5808/Manifest/Details?id=80004
CSHTML:
<form method="post">
<input type="image" data-id="#Model.ManifestViewModel.ID" asp-page-handler="CreateTwitterItem" src="~/images/twitterlogo.jpg" name="New Twitter" id="CreateNewTwitterData" />
</form>
C#:
[ValidateAntiForgeryToken]
public async Task<IActionResult> OnPostCreateTwitterItemAsync(long? id)
{
if (!ModelState.IsValid)
{
return Page();
}
return new JsonResult("Hello world");
}
I have tried the ajax method below but the code does not reach the success point.
$('#CreateNewTwitterData').click(function (e) {
$.ajax({
type: "POST",
url: '/Manifest/Details?id=' + $(CreateNewTwitterData).data("id") + '&handler=CreateTwitterItem', // <-- Where should this point?
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
dataType: "json"
}).done(function (data) {
alert(data);
})
})
I have found an Ajax solution using.Netcore 2.0 razor page after trial and error but I am not sure if it is the best solution It worked for me so I thought I would share it.(In addition, I realised I didn't need the form tags in the cshtml with asp-page-handler this was making its own call ).
CSHTML:
<img type="image" class="socialmediaicon" data-id="#Model.ManifestViewModel.ID" src="~/images/twitterlogo.jpg" name="New Twitter" id="CreateNewTwitterData" asp-route-id="#Model.ManifestViewModel.ID" height="20" width="20" />
AJAX:
$('#CreateNewTwitterData').click(function (e) {
$.ajax({
type: "POST",
url: "/Manifest/Details?id=" + $(CreateNewTwitterData).data("id") + "&handler=CreateTwitterItem", // <-- Where should this point?
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
dataType: "json", success: function (msg) {
alert("success");
alert(msg);
},
error: function (errormessage) {
alert("fail");
}
})
})
In this code returned json from controller shows 5 items but it's duplicates in the ajax call success function.
Html
<select class="form-control id="books">
</select>
My Ajax Call
function LoadBooks(rackNo) {
debugger;
$.ajax({
url: '#Url.Action("GetBookDetails", "Books")',
type: "POST",
async: false,
data: JSON.stringify({ rackNo: rackNo }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (_booklst) {
debugger;
console.log(_booklst);
$('#books').empty();
$.each(_booklst, function (index, item) {
$('#books').append($('<option><option/>').val(item.bookno).text(item.bookname));
});
}
});
}
You need to change
$.each(_booklst, function (index, item) {
$('#books').append($('<option><option/>').val(item.bookno).text(item.bookname));
});
to
$.each(_booklst, function (index, item) {
$('#books').append($('<option></option>').val(item.bookno).text(item.bookname));
});
(the position of the / in '<option></option>')
Here is the problem. Use
<select class="form-control" id="books"> </select>
instead of
<select class="form-control id="books">
</select>
Ok so I have a couple of input fields etc I send the data of these field to server side webmethod . WHich is working fine. But I also want to send files to the same webmethod (and not ashx hander) alond with the data of other input fields. Can you please help me out?
This calls webmethod which stored data in database
function SendToServer(name,lineitems) {
$.ajax({
type: "POST",
url: "test.aspx/PostDataWM",
data: JSON.stringify({ name: name,lineitems: lineitems }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
// console.log("CallWM");
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
}
File Upload MarkUp
<span style="font-family: Arial">Click to add files</span>
<input id="Button1" type="button" value="add" onclick="AddFileUpload()" />
<br />
<br />
<div id="FileUploadContainer">
<!--FileUpload Controls will be added here -->
</div>
<script type="text/javascript">
var counter = 0;
function AddFileUpload() {
var div = document.createElement('DIV');
div.innerHTML = '<input id="file' + counter + '" name = "file' + counter + '" type="file" class="clsFileUpload" /><input id="Button' + counter + '" type="button" value="Remove" onclick = "RemoveFileUpload(this)" />';
document.getElementById("FileUploadContainer").appendChild(div);
counter++;
}
function RemoveFileUpload(div) {
document.getElementById("FileUploadContainer").removeChild(div.parentNode);
}
</script>
WebMethod
[WebMethod(enableSession: true)]
public static string PostDataWM(string name,string lineitems)
{
//blah blah
}
No need to stringify the data.
Try it directly. You can get data at your code level
type: "POST",
url: "test.aspx/PostDataWM",
data: { name: name,lineitems: lineitems },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
var formData = new FormData($("form#neweventform")[0]);
$.ajax({
url: "/Event/NewEvent",
type: "POST",
data: formData,//JSON.stringify(saveEventModel),
async: false,
dataType: 'json',
//contentType: 'application/json; charset=utf-8',
cache: false,
contentType: false,
processData: false,
fail: function (r) {
alert('error.');
},
success: function (result) {
}
...
On the controller side I have:
public JsonResult NewEvent(EventModel saveEventModel, List<HttpPostedFileBase> files)
{
}
I receive file in List<HttpPostedFileBase> files object but it's null. May be data is not posted to the server?
I think I'm doing something wrong conceptually. :/
How to upload images together with other form data like name, date, address etc.?..
Is this what you're looking for?
C# MVC controller
public class UploadController : Controller
{
[HttpPost]
public JsonResult FilesList(List<HttpPostedFileBase> myFiles)
{
string message;
if (myFiles == null)
{
message = "myFiles is null";
}
else if (myFiles.Count != 2)
{
message = "myFiles.Count is " + myFiles.Count;
}
else
{
message = string.Format("myFiles[0] is {0}, myFiles[1] = {1}",
myFiles[0] == null ? "null" : myFiles[0].FileName,
myFiles[1] == null ? "null" : myFiles[1].FileName);
}
return Json(new
{
Message = message
});
}
}
HTML + Javascript
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Upload Demo </title>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function ()
{
$('#sendButton').click(function ()
{
var form = $('#myForm')[0];
var formData = new FormData(form);
$.ajax({
data: formData,
processData: false,
contentType: false,
dataType: 'json',
type: 'POST',
url: 'Upload/FilesList',
error: function (jqXHR, textStatus, errorThrown)
{
alert('failure\n' + textStatus);
},
success: function (data, textStatus, jqXHR)
{
alert(data.Message);
}
});
});
});
</script>
</head>
<body>
<form id="myForm">
File 1: <input type="file" name="myFiles" /><br />
File 2: <input type="file" name="myFiles" />
</form>
<button id="sendButton">Submit over AJAX</button>
</body>
</html>
I have button and that jQuery script (to start the progress bar):
<script src="../_Files/JScripts/jquery-1.3.2.js" type="text/javascript"></script>
<script src="../_Files/JScripts/jquery-ui-1.7.2.custom.min.js" type="text/javascript"></script>
var intervalID;
$("#<%=this.Button1.ClientID%>").click(
function() {
intervalID = setInterval(updateProgress, 500);
$.ajax({
type: "POST",
url: "CustomerImport.aspx/ExecuteImport",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function()
{
$("#progressbar").progressbar("value", 100);
clearInterval(intervalID);
$("#result").text('ok');
}
});
return false;
}
);
function updateProgress() {
$.ajax({
type: "POST",
url: "CustomerImport.aspx/GetProgress",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) {
$("#result").text = msg.d;
var value = $("#progressbar").progressbar("option", "value");
if (value < 100) {
$("#progressbar").progressbar("value", msg.d);
$("#result").text(msg.d);
}
else {
clearInterval(intervalID);
window.location = window.location;
}
}
});
}
the method:
[System.Web.Services.WebMethod]
public void ExecuteImport()
{
_Presenter.ExecuteImport();
}
the problem is, that method is NOT being invoked. Why ?
When I replace the $.ajax for the e.g alert('ok'); the alert shows, so it works
Did you decorate your service class with the [ScriptService] attribute? Also try changing the data parameter to: data: { }. What does FireBug says about this? Is there a request being sent? If yes what does the server respond?
Also you have a mistake in your url (web services have the ASMX extension). You wrote:
CustomerImport.aspx/ExecuteImport
While it should be:
CustomerImport.asmx/ExecuteImport
Here's a complete working example that you may adapt to your needs:
Web service:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[ScriptService]
public class CustomerImport : WebService
{
[WebMethod]
public void ExecuteImport()
{
}
}
Calling web page:
<%# Page Language="C#" %>
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript" src="scripts/jquery-1.4.1.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: 'POST',
url: '/CustomerImport.asmx/ExecuteImport',
data: { },
success: function () {
alert('ok');
}
});
});
</script>
</head>
<body>
<form runat="server">
</form>
</body>
</html>
Add in the error function to the ajax call... Hopefully you'll get some info back, as to why the call failed.
Are you using firebug? Watch the net tab.
$.ajax({
type: "POST",
url: url,
async: false,
data: jsonEncodedParams,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
}, //success
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (textStatus == "timeout") {
alert('The request timed out, please resubmit');
} //if
else {
alert(errorThrown);
} //else
} //error
}); //ajax
Since your server-side endpoint is a "page method", it must be declared as static:
[System.Web.Services.WebMethod]
public static void ExecuteImport()
{
_Presenter.ExecuteImport();
}