using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace MyAJaxTest.Models
{
[Table("Destinations")]
publicclass Destination
{
[Key]
publicstring City { get; set; }
publicstring Country { get; set; }
publicint Id { get; set; }
publicDestination(string city, string country, int id = 0)
{
City = city;
Country = country;
Id = id;
}
publicDestination() { }
}
}
AjaxContext.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data;
using System.Data.Entity;
namespace MyAJaxTest.Models
{
publicclass AjaxContext : DbContext
{
publicvirtual DbSet<Destination> Destinations { get; set; }
publicAjaxContext()
: base("DefaultConnection")
{
}
}
}
HomeController.cs
using MyAJaxTest.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MyAJaxTest.Controllers
{
publicclass HomeController : Controller
{
private AjaxContext db = new AjaxContext();
public ActionResult RandomDestinationList(int destinationCount)
{
var randomDestinationList = db.Destinations.OrderBy(r => Guid.NewGuid()).Take(destinationCount);
return Json(randomDestinationList, JsonRequestBehavior.AllowGet);
}
public ActionResult Index()
{
return View();
}
public ActionResult HelloAjax()
{
return Content("你好!来自控制器!", "text/plain");
}
public ActionResult Sum(int firstNumber, int secondNumber)
{
return Content((firstNumber + secondNumber).ToString(), "text/plain");
}
public ActionResult DisplayObject()
{
Destination destination = new Destination("东京", "日本", 1);
return Json(destination, JsonRequestBehavior.AllowGet);
}
public ActionResult DisplayViewWithAjax()
{
return View();
}
[HttpPost]
public ActionResult NewDestination(string newCity, string newCountry)
{
Destination newDestination = new Destination(newCity, newCountry);
db.Destinations.Add(newDestination);
db.SaveChanges();
return Json(newDestination, JsonRequestBehavior.AllowGet);
}
}
}