call an Asp Action from javascript - javascript

I have a table that will use is populated by javascript when another table option is clicked. All of this works no problem, when I add the delete button to the table the onClick event fires but this isn't ever called in asp.net.
function DeleteLink(id) {
$.ajax({
url: '/PublicPages/LinkDelete/',
data:{ id:id }
});
}
please tell me where I've gone wrong.
I have tried
function DeleteLink(id) {
$.ajax({
url: '/PublicPages/LinkDelete/' + id
}
as well
UPDATE:
[HttpPost]
public async Task<IActionResult> LinkDelete(Guid id)
{
var pageId = _linkDataProvider.FindById(id).PublicPage.Id;
_linkDataProvider.Delete(id);
var page = await _pageDataProvider.FindById(pageId);
var viewModel = _pageDataProvider.ConvertToViewModel(page);
return View("Details", viewModel);
}
UPDATE2
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Flooring}/{action=Index}/{id?}");
});

You should specify http method in ajax settings. Try to change your javascript like below:
function DeleteLink(id) {
$.ajax({
type = 'POST',
url: '/PublicPages/LinkDelete/' + id
});
}
Update
If you prefer to use data:{ id:id } then you would need to create a model class:
public class DeleteModel
{
public Guid Id{get;set;}
}
[HttpPost]
public async Task<IActionResult> LinkDelete([FromBody]DeleteModel model)
....

Related

POST and GET methods on the same button

I am currently learning asp.net core 3 and I can't find any help regarding this issue that I have.
I have a form that submits a value with a POST request. But I want the same button to have a GET request that populates another field with a .ajax / xmlhttprequest. But I want the POST method to be executed first and then the GET method. Is it possible to do it? I've tried doing it but I got stuck.
These are the methods inside my controller.
[HttpGet]
public async Task<IActionResult> GetConvertedAmount()
{
var rate = await _db.ExchangeRates.Where(x => x.Name.Equals(_tM.Currency)).ToListAsync();
_tM.convertToCurrency(rate[0].Rate);
var amount = _tM.Amount;
return Json(amount);
}
[HttpPost]
public ActionResult CalculateExchangeRatio(int amount_give, string type_to_give)
{
_tM.Amount = amount_give;
_tM.Currency = type_to_give;
return Ok();
}
And this is my JS script
$('#calculateButton').on("click", function () {
$.ajax({
url: "/trade/getconvertedamount",
type: "get",
success: function (amount) {
console.log(amount);
alert(amount);
}
});
})
You can use the $.ajax 'done' chaining to complete the entire process:
$('#calculateButton').on("click", function () {
$.ajax({
url: "/trade/calculateexchangeratio",
data: { amount_give: 9.99, type_to_give: 'blahblah' },
type: "post"
})
.done(function(){
$.ajax({
url: "/trade/getconvertedamount",
type: "get"
})
.done(function (amount) { console.log(amount); alert(amount); });
});
})
You can add the similar to the end of the POST method implementation return RedirectToAction("CalculateExchangeRatio", new { amount_give = 1, type_to_give = 2 });
So your POST method will be called first and it will call the GET method.
Here is the documenttation.

Passing parameters in Ajax post back in MVC

I am trying to pass ID parameter from a view to a controller on a click delete link available on a selected row.
Simplified View Layout
#using (Html.BeginForm("#", "Schedule", FormMethod.Post, htmlAttributes: new { #class = "floating-labels" }))
{
#Html.AntiForgeryToken()
Delete
}
JavaScript
<script type="text/javascript">
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
$.ajax({
type: "POST",
url: '#Url.Action("Delete", "Schedule", new { id = "id" })',
contentType: "application/json",
data: { id },
async: true,
cache: false,
success: function (result) { success(result); }
});
}
return false;
}
function success(result) {
$("#ScheduleList").html(result);
}
</script>
Controller
namespace Controllers
{
public class ScheduleController
{
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
//do stuff
}
}
}
But on the click of a delete link I get below error and code does not hit controller action.
I am not able to figure out what mistake I am making...
Here is my locally tested implementation that is working.
ScheduleController class:
public class ScheduleController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Delete(int id)
{
return Ok(id);
}
}
Page that sends the post request:
#Html.AntiForgeryToken()
Delete
<div id="ScheduleList"></div>
<script>
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
var uri = '/Schedule/Delete?id=' + id;
var tokenElement = document.getElementsByName('__RequestVerificationToken')[0];
var data = {
__RequestVerificationToken: tokenElement.value
}
$.ajax({
type: "POST",
url: uri,
data: data,
success: function (result) {
success(result);
}
});
}
return false;
}
function success(result) {
$("#ScheduleList").html(result);
}
</script>
The page does nothing but render the html, and the javascript handles the actual Ajax post. What I believe you were missing is the Validation token in your request.
It is because you are not actullay posting the form pass it correctly and add _token in the ajax data list and value for that token will come from #Html.AntiforgeryToken()
reading the error the request is most probably send correctly and there is an internal server error as mentioned in the 500 respond so please check the code that is inside the controller
Try this, you are accesing a javascript variable on c# code, and you cant do that.
If correct, please mark as answer.
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
var url = '#Url.Action("Delete", "Schedule")?id=' + id;
$.ajax({
type: "POST",
url: url,
contentType: "application/json",
data: { id },
async: true,
cache: false,
success: function (result) { success(result); }
});
}
return false;
}
I think none of the answers above solve the issue. First of all I would replace your target url:
url: '#Url.Action("Delete", "Schedule", new { id = "id" })',
with
url: '#Url.Action("Delete", "Schedule", new { id = actualIdVariable })',
(replace "id" with the actual id variable from the model you're passing to the view).
Note how your browser response is telling you that the url you're posting to is Schedule/Delete/id. That said, I'm not sure you even need the routeValues in this case (the new { id = ...} parameter). this is a POST action, and action parameters wouldn't come from route unless specified by by attribute routing (i.e. [Route("~/Schedule/Delete/{id}")] attribute on your action).
I think your post action is failing because it is trying to parse the "id" string as an int.
Second, I would change the data property of the ajax call and include the anti forgery token. Just because the anchor element you're binding the click event to, is inside the form with #Html.AntiforgeryToken() doesn't mean the generated token will be posted in the ajax request. You're not actually submitting/posting the form, you're just clicking a button.
it should be something like
data: {
'id': id,
'__RequestVerificationToken': $('[name="__RequestVerificationToken"]').val()
}
try this, it solve the error on routing (different url Action) and the parameter on the controller:
JavaScript
<script type="text/javascript">
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
$.ajax({
type: "POST",
url: '#Url.Action("Delete", "Schedule")',
data: "id=" + id ,
async: true,
cache: false,
success: function (result) { success(result); }
});
}
return false;
}
function success(result) {
$("#ScheduleList").html(result);
}
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(string id)
{
//do stuff
}
Nicola.

Passing ViewModel back from controller to Javascript Function MVC

So I have a ViewModel that holds some basic information, and I am taking in an input from the view. Then the input is sent to a .js function that sends it to a controller function that does some work with it. Right now I am just trying to get the Javascript function to connect and display some irrelevant code on the page just to make sure its connected. I make it through everything with no errors, and at the very end I am returned the errorOnAjax Function, inside of the browser tools, that I have written myself. So there is no problem with any of the code that I can see.
My thought is, I am converting the ViewModel to Json wrong in the controller, in turn, it is returning it the wrong way to the Javascript function and giving the error. If anyone has any suggestions, it would be greatly appreciated!
public class MapInfoViewModel
{
public string Place { get; set; }
public string City { get; set; }
public string State { get; set; }
public string URL { get; set; }
}
And I am getting information from the view via an input box
#using (Html.BeginForm())
{
<input type="text" id="name" />
<button id="myButton" onclick="getInfo()">AJAX</button>
}
This is what my Javascript Function looks like. showInfo is just injecting a basic table into the view with just 1 value inside, just to make sure it is connected.
function getInfo(Info) {
var myInfo = document.getElementById('name').value;
$.ajax({
type: "GET",
dataType: "json",
url: "/CreateRoute/DisplayInfo",
data: { 'myInfo': myInfo },
success: showInfo,
error: errorOnAjax
})
}
and my Controller Function
public ActionResult DisplayInfo()
{
string request = Request.QueryString["myInfo"];
MapInfoViewModel info = new MapInfoViewModel()
{
Place = request
};
return new ContentResult
{
Content = JsonConvert.SerializeObject(info),
ContentType = "application/json",
ContentEncoding = System.Text.Encoding.UTF8
};
}
You wrote everything correct code but you just miss the one attribute in view.
you need to mention button type then it will work as per your expectations
<button id="myButton" onclick="getInfo()">AJAX</button>
Now I sharing the complete details of this issue.
Javascript-
function getInfo(Info) {
var myInfo = document.getElementById('name').value;
$.ajax({
type: "GET",
dataType: "json",
url: "/Test/DisplayInfo",
data: { 'myInfo': myInfo },
success: showInfo,
error: errorOnAjax
})
function showInfo(result) {
console.log(result);
}
function errorOnAjax() {
console.log("errorOnAjax");
}
}
View -
#using (#Html.BeginForm())
{
<input type="text" id="name" />
<button type="button" id="myButton" onclick="getInfo()">AJAX</button>
}
Controller-
public ActionResult DisplayInfo()
{
string request = Request.QueryString["myInfo"];
MapInfoViewModel info = new MapInfoViewModel()
{
Place = request
};
return new ContentResult
{
Content = JsonConvert.SerializeObject(info),
ContentType = "application/json",
ContentEncoding = System.Text.Encoding.UTF8
};
}
First return with json in controller.
public ActionResult DisplayInfo(string myInfo)
{
MapInfoViewModel info = new MapInfoViewModel()
{
Place = myInfo
};
return Json(info,JsonRequestBehavior.AllowGet);
}
In Front End use ajax like this.
$( "#myButton" ).click(function() {
let data={myInfo:$('#name').val();};
$.ajax({
type: "GET",
dataType: "json",
url: "/CreateRoute/DisplayInfo",
data: data,
success: function (response){
//do
},
error: function (error){
}
});
});
You need to create JsonResult function, then return Json(info, JsonRequestBehavior.AllowGet) as #sadullah zolfqar answered you.
Please refer to the below link to get the full explanation:
https://www.c-sharpcorner.com/UploadFile/2ed7ae/jsonresult-type-in-mvc/

New Razor Pages from javascript with posting data

How can I post data with javascript followed by loading a new Razor Page?
If I call a new Razor Page from an Ajax call then I canĀ“t return that new Page.
How can I achieve this?
Thank you
Client: Javascript on Razor Page1.cshtml
var ptFilter = (...);
// $.ajax ??? call post Method of Page2
Server: another razor page Page2.cs
public async Task OnPostSendAsync([FromBody]PtFilter ptFilter)
{
var data = await _ptService.GetData(ptFilter);
// RedirectToPage(data) ??;
// return Page(data) ??;
}
You can post data via $.ajax and receive a response from your controller, then just use window.location.replace(your page2 action url here)
Something like that:
$.ajax({
url: "...",
//...
}).done(function(data) {
//If needed, check received data, then
window.location.replace(your page2 action url here);
});
Please take notes of the $ajax.url and the #ajax.success() that contains updatePreviewCart()
In the example below of a razor pages application I've been working on, I am adding a product item from the product page to a shopping cart view component that belongs on the navigation menu of the site. Once the item has been added to the shopping cart's database, the returning success block of the ajax call in the first code snippet will update the shopping cart on the nav bar. The ViewComponent is loaded via a BaseController as the component is being used within the _Layout.cs file.
Products.html
$(".add-to-cart").on("click", function (element: any) {
element.preventDefault();
$.ajax({
cache: false,
type: "POST",
url: "Products/?handler=AsyncAddToCart",
data: { id: $(this).data("id") },
beforeSend: xhr => {
xhr.setRequestHeader("XSRF-TOKEN", ($('input:hidden[name="__RequestVerificationToken"]').val() as string));
},
success: (data) => {
if (data.isSuccess) {
toastr.success($(this).data("name") + " has successfully been added to your cart. <a href='/Index'>Go to checkout</a>");
updatePreviewCart();
} else {
toastr.error(data.message);
}
},
error: (xhr: any, ajaxOptions: any, thrownError: any) => {
toastr.error("Unable to add items at this time. Please try again later or contact support if issue persists.");
}
});
});
UpdateCartPreview.js
function updatePreviewCart() {
$.ajax(({
cache: false,
type: "GET",
url: "/Base/GetCartViewComponent",
success: (data) => {
$("#preview-cart-container").html(data);
},
error: (xhr: any, ajaxOptions: any, thrownError: any) => {
toastr.warning("Your preview cart is still updating. You should see your added item(s) shortly.");
}
}));
}
BaseController.cs
[Route("[controller]/[action]")]
public class BaseController : Controller
{
[HttpGet]
public IActionResult GetCartViewComponent()
{
return ViewComponent("Cart");
}
[HttpPost]
public IActionResult SetLanguage(string culture, string returnUrl)
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1)}
);
return LocalRedirect(returnUrl);
}
}
Cart.cs View Component
public class Cart : ViewComponent
{
private readonly ICartService _cartService;
public Cart(ICartService cartService)
{
_cartService = cartService;
}
public async Task<IViewComponentResult> InvokeAsync()
{
return View("~/Pages/Components/Cart/Default.cshtml", await _cartService.GetCart());
}
}

Problems updating database with Jquery.Ajax

I am working on a website and would like to be able to update a field on a database table when a div is clicked. I found some example code right here on stack but for some reason it won't work, even though it was accepted. I am using C# ASP.NET MVC Razor.
My JavaScript function is as follows:
function toggleContent(id, instID) {
var doc = document.getElementsByClassName("messageContent")[id];
$(doc).slideToggle();
$.ajax({
type: 'POST',
url: "#Url.Content('/Messages/MarkSeen/')",
data: {
instanceID : instID
},
dataType: 'json'
});
}
And my JsonResult is as follows:
[HttpPost]
public JsonResult MarkSeen(int instanceID)
{
var markSeen = db.MessageInstances.First(mi => mi.MessageInstanceId == instanceID);
if (markSeen.RegisteredPerson.PersonId == CurrentUser.PersonId)
{
markSeen.Seen = true;
db.SaveChanges();
return Json(true);
}
return Json(false);
}
I'm not sure where your code fails, so I posted complete working code
If you are using the ApiController, please try the following updates to make your code works:
1. add route to WebApiConfig.cs
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
2. javascript
$.ajax({
type: "POST",
url: "#Url.Content("/api/lab/MarkSeen")",
data: { "instanceID": instID },
dataType: 'json',
success: function (data) { alert(data)},
error: function () { alert('error'); }
});
3. Add model to match the json from ajax request:
public class labModel
{
public int instanceID { get; set; }
}
4. Controller:
[System.Web.Mvc.HttpPost]
public JsonResult<bool> MarkSeen(labModel data)
{
return Json(true);
}

Categories

Resources