在Asp.Net MVC 4中使用AJAX提交表单。
在Asp.Net MVC 4中使用AJAX提交表单。
我正在努力学习asp.net,到目前为止,我可以使用
控制器页面
命名空间CrudMvc.Controllers
{
public class HomeController:Controller
{
sampleDBEntities db = new sampleDBEntities();
//
// GET:/Home/
public ActionResult Index()
{
return View(db.myTables.ToList());
}
public PartialViewResult Details(int id = 0)
{
myTable Table = db.myTables.Find(id);
return PartialView(Table);
}
[HttpGet]
public PartialViewResult Create()
{
return PartialView();
}
[HttpPost]
public ActionResult Create(myTable table)
{
if (ModelState.IsValid)
{
db.myTables.Add(table);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(table);
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
Index视图页面
@model IEnumerable
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
Index
@Ajax.ActionLink("Add New", "Create", new AjaxOptions()
{
HttpMethod = "GET",
UpdateTargetId = "info",
InsertionMode = InsertionMode.Replace
})
@Html.DisplayNameFor(model => model.name) |
Action |
---|---|
@Html.DisplayFor(modelItem => item.name) |
@Ajax.ActionLink("Details", "Details", new{ id=item.id}, new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = "info", InsertionMode = InsertionMode.Replace }) |
Create视图页面
@model CrudMvc.Models.myTable
@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
Create
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
}
var form = $('#main');
$.ajax({
cache: false,
async: true,
type: "POST",
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
alert(data);
}
});
@Html.ActionLink("Back to List", "Index")
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}