在Asp.Net MVC 4中使用AJAX提交表单。

15 浏览
0 Comments

在Asp.Net MVC 4中使用AJAX提交表单。

我正在努力学习asp.net,到目前为止,我可以使用在不刷新页面的情况下加载其他页面内容,但是我无法弄清楚如何在提交表单时使用ajax。我进行了很多搜索,但找不到合适的解决方案。以下是我的代码,

控制器页面

命名空间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

})

@foreach (var item in Model) {

}

@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)

myTable

@Html.LabelFor(model => model.id)

@Html.EditorFor(model => model.id)

@Html.ValidationMessageFor(model => model.id)

@Html.LabelFor(model => model.name)

@Html.EditorFor(model => model.name)

@Html.ValidationMessageFor(model => model.name)

}

@Html.ActionLink("Back to List", "Index")

@section Scripts {

@Scripts.Render("~/bundles/jqueryval")

}

0