[Fork] MVC-AJAX Test

CSharp · Mvc

Model

using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;

namespace HelloWorldMvcApp
{
	public class Category
    {
        public int Id { get; set; }

        public string CategoryName { get; set; }

        public static List<Category> GetCategories()
        {
			System.Threading.Thread.Sleep(10000);
            List<Category> result = new List<Category>()
			{
				new Category { Id = 1, CategoryName = "First" },
				new Category { Id = 2, CategoryName = "Second" },
				new Category { Id = 3, CategoryName = "Third" }
			};

            return result;
        }
    }
}

View

@model HelloWorldMvcApp.Category
@{
	Layout = null;
}

<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->

<html lang="en">
	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>Bootstrap 101 Template</title>

		<!-- CSS Includes -->
		<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
		
		<style type="text/css">

			.field-validation-error {
				color: #ff0000;
			}

		</style>
	</head>
	
	<body>
		<div class="container">
			<div class="col-md-6 col-md-offset-3">
				<button id="btnTest" type="button" class="btn btn-success submit">Ask</button>
				<br/><br/>
			</div>
			<div id="result">
			</div>
		</div>

		<!-- JS includes -->
		<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
		<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
	
		<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
		<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
		
		<script type="text/javascript">
		
			$(function(){
				
				$('#btnTest').click(function(){
			
					var myID = 7;
			
					$.ajax({
						url: '@Url.Action("SomeAction", "Home")',
						dataType: 'json',
						data: { id: myID },
						type: 'POST',
						success: function (response) {
							if (response.ok) {
								// When everything is ok
								console.log(response.data);
			                    var html = "";
			                    for(var idx in response.data) {
									var category = response.data[idx];
									html += "<p>Id = " + category.Id + ",&nbsp;Name = " + category.CategoryName + "</p>";
			                    }
								$("#result").append(html);
							} else {
								// When an exception is thrown
								console.log("An error occurred :  " + response.data);
							}
						},
						error: function (error) {
							console.log("An error occurred :  " + error.responseText);
						}
					});
				});
			});

		</script>
	</body>
</html>

Controller

using System;
using System.Web.Mvc;
using System.Collections.Generic;

namespace HelloWorldMvcApp
{
	public class HomeController : Controller
	{
		[HttpGet]
		public ActionResult Index()
		{
			return View(new Category());
		}

		[HttpPost]
		public JsonResult SomeAction(int id)
		{
			try
			{
				//Foo foo = new Foo();
				//var actionResult = foo.DoSyncAction(id);
				var actionResult = Category.GetCategories();

				return Json(new { ok = true, data = actionResult }, JsonRequestBehavior.AllowGet); ;
			}
			catch (Exception ex)
			{

				return Json(new { data = ex == null ? "null ex" : (string.IsNullOrEmpty(ex.Message) ? "this exception is empty" : ex.Message) }, JsonRequestBehavior.AllowGet);
			}
		}
	}
}
;