1

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

8 Comments

note the [HttpGet] is optional as the action will default to a GET
yes it is optional you can ignore it by default it will be get.
I tried but still showing the same error, it is not calling the method at all. I set a breakpoint and checked
what is your controller name?what is the base type of it?
public class ProductsController : Controller
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.