Reputation: 59
I created an action in mvc, and I tried to call the action using jquery.get. The resulting response was not found(404)
. Following is the action method and jquery
code.
Error:
GET http://localhost:52050/Products/PriceWithTax?pid=1 404 (Not Found)
Latest Jquery 3.4.1
is included in Bundle.config
.
Action Method in MVC
public decimal PriceWithTax(int pid)
{
ApplicationDbContext dbContext = new ApplicationDbContext();
var product = dbContext.Products.FirstOrDefault(x => x.Id == pid);
return (decimal)((product.Price * 0.18m) + product.Price);
}
Jquery in .cshtml page
@section Scripts{
<script>
jQuery(document).ready(function(){
jQuery("#Id").blur(function () {
var productId = $(this).val();
var tax = jQuery("#txtTax");
jQuery.get('@Url.Action("PriceWithTax","Products")', { pid: productId }, function (data) {
tax.val(data);
});
//jQuery.get('/Products/PriceWithTax', { pid: productId }, function (data) {
// tax.val(data);
//});
});
});
</script>
}```
I tried $ instead on jQuery and get instead of post
Upvotes: 1
Views: 294
Reputation: 2348
Change your action method to return JsonResult
rather than decimal
as following:
public JsonResult PriceWithTax(int pid)
{
ApplicationDbContext dbContext = new ApplicationDbContext();
var product = dbContext.Products.FirstOrDefault(x => x.Id == pid);
var value = (decimal)((product.Price * 0.18m) + product.Price);
return Json(value,JsonRequestBehavior.AllowGet);
}
for more documentation about action result types check this link
Upvotes: 1