第七章 模态框
1.在Index.cshtml中添加创建按钮
<a class="btn btn-success" href="@Url.Action("create" })" data-toggle="x-modal" data-modalId="@(Guid.NewGuid().ToString("N"))" > <span class="glyphicon glyphicon-plus"></span>创建</a>
2.控制器
[HttpGet] public ActionResult Create() { ViewBag.ModalID = Request["ModalID"]; StudentModel model = new StudentModel(); model.StatusID = 1; return View("CreateOrEdit",model); }
3.html代码
CreateOrEdit.cshtml代码
@{ var action = ViewContext.RouteData.Values["Action"].ToString().ToLower(); ViewBag.Title = action == "create" ? "添加信息" : "修改信息"; Layout = "~/Views/Shared/_FormMaster.cshtml"; } @model Models.Students.StudentsModel <div id="form-content" class="container"> @using (Ajax.BeginForm(action, "Students", new { area = "Students" }, new AjaxOptions { OnSuccess = "onsuccess", HttpMethod = "Post", UpdateTargetId = ViewBag.ModalID, InsertionMode = InsertionMode.Replace }, new { @class = "form-horizontal", role = "form" })) { //模态框 ID <input type="hidden" name="ModalID" value="@ViewBag.ModalID" /> if (!string.IsNullOrEmpty(ViewBag.FormCode)) { //表单状态代码 <input type="hidden" name="FormCode" id="@(ViewBag.ModalID + "_FormCode")" value="@ViewBag.FormCode" /> } <div class="modal-dialog" style="width: 400px;"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> ×</button> <h4 class="modal-title" id="myModalLabel">@ViewBag.Title</h4> </div> <div class="modal-body"> @Html.HiddenFor(t => t.ID) <div class="form-group"> <label class="control-label col-md-3"> @Html.LabelFor(t => t.Name)</label> <div class="col-md-8 input-group"> @Html.TextBoxFor(t => t.Name, new { @class = "form-control " }) @Html.ValidationMessageFor(t => t.Name, null, new { @class = "input-group-addon" }) </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal"> 关闭</button> <button type="submit" class="btn btn-primary"> 保存</button> </div> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> } <script type="text/javascript"> function onsuccess() { var ModalID = "@ViewBag.ModalID"; if ($('#' + ModalID + "_FormCode").val() == "1") { alert("提示", "保存成功!"); } refresh(); } </script> </div>
4.提交表单
[HttpPost] public ActionResult Create(StudentsModel model) { ViewBag.ModalID = Request["ModalID"]; if (ModelState.IsValid) { //添加餐桌 var result = InsertRule( model.ID, model.Name ); if (result.IsOK) { //成功 ViewBag.FormCode = "1"; } } return View("CreateOrEdit", model); }