<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
$(function () {
$("#theBtn").click(function () {
$.ajax({
type: "GET",
url: '@Url.RouteUrl(new{ action="GetAnswer", controller="Home"})', //I changed this url
async: false,
cache: false,
dataType: "json",
contentType: "application/json",
success: function (jsn) {
alert(jsn);
},
error: function (error) {
alert("error");
console.log(error);
}
});
</script>
</head>
<body>
<div>
<input type="button" id="theBtn" value="Click to start ajax" />
</div>
</body>
</html>
using System;
using System.Web.Mvc;
using System.Collections.Generic;
namespace HelloWorldMvcApp
{
public class HomeController : Controller
[HttpGet]
public ActionResult Index()
return View();
public JsonResult GetAnswer(string question)
try
throw new Exception("Luke Perrin shows exception");
catch (Exception ex)
return Json(ex.Message, JsonRequestBehavior.AllowGet);