学海无涯

导航

jQuery AJAX and JSON Example in ASP.Net Core MVC

 

 public class PersonModel
    {
        public string Name { get; set; }
        public string DateTime { get; set; }
    }

 

   public class PersonController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public JsonResult AjaxMethod(string name)
        {
            PersonModel model = new PersonModel
            {
                Name = name,
                DateTime = DateTime.Now.ToString(),
            };
            return Json(false);
            return Json(model);
        }
    }
<input type="text" id="txtName" />
<input type="button" id="btnGet" value="Get Current Time" />

@section Scripts {
    <script>
        $(function () {
            $("#btnGet").click(function () {
                $.ajax({
                    type: "POST",
                    url: "/Person/AjaxMethod",
                    data: { "name": $("#txtName").val() },
                    success: function (response) {
                        alert("Hello: " + response.name + " .\nCurrent Date and Time: " + response.dateTime);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            });
        });
    </script>
}

 

 

posted on 2023-02-21 17:25  宁静致远.  阅读(55)  评论(0编辑  收藏  举报