【发布时间】:2017-05-03 08:15:38
【问题描述】:
我已经为我的树视图列表创建了 CRUD 操作,但它们是静态的 - 页面会在将数据提交到控制器时重新加载。如何使其动态化,以便在添加、删除或编辑元素时无需重新加载页面。 在这种情况下,我只想知道如何为 ADD 操作做到这一点。
查看:
@helper PopulateDivs(List<Tree_List.Controllers.Element> elements)
{
<ul>
@foreach (var element in elements)
{
<li>
<div class="element_wrapper" data-id="@element.ID" data-parent="@element.PARNET_ID" @*style="display:none"*@>
<button class="toggler_btn" type="button" data-id="@element.ID" data-parent="@element.PARNET_ID">+</button>
@element.NAME
<button class="add_btn" type="button" data-id="@element.ID">Add</button>
<button class="edit_btn" type="button" data-id="@element.ID" data-parent="@element.PARNET_ID">Edit</button>
<button class="delete_btn" type="button" data-id="@element.ID">Delete</button>
<ul id="childItems-@element.ID"></ul>
</div>
</li>
}
</ul>
}
控制器创建方法:
//MODAL POPUP FOR CREATE
public ActionResult CreateNewItem(int id)
{
if (id == 0)
{
H_Table item = new H_Table();
return PartialView(item);
}
else
{
H_Table item = db_connection.H_Table.Find(id);
return PartialView(item);
}
}
//POST: CREATE ITEM
[HttpPost]
// [ValidateAntiForgeryToken]
public ActionResult CreateNewItem(string name, int parent)
{
H_Table item = new H_Table();
if (parent == 0)
{
item.NAME = name;
item.PARENT_ID = null;
}
else
{
item.PARENT_ID = parent;
item.NAME = name;
}
if (ModelState.IsValid)
{
db_connection.H_Table.Add(item);
db_connection.SaveChanges();
return RedirectToAction("Index");
}
return View(item);
}
JS:
$('body').on('click', '.add_btn', function () {
$.get("/List/CreateNewItem", { id: $(this).data('id') }, function (data) {
$('#modal_window').replaceWith('<div id="modal_window">' + data + '</div>');
$('#modal_window').show();
});
});
创建的局部视图:
@model Tree_List.Models.H_Table
<form action="/List/CreateNewItem" method="post">
<div class="form-horizontal">
<h4>CREATE NEW ITEM</h4>
<div class="form-group">
<div class="control-label col-md-2">NAME</div>
<div class="col-md-10">
<input name="name" type="text" value="" />
</div>
</div>
<div class="form-group">
<div class="control-label col-md-2">PARENT</div>
<div class="col-md-10">
<input name="parent" type="text" value="@Model.ID" readonly />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
</form>
<div>
@Html.ActionLink("Back to List", "Index")
</div>
【问题讨论】:
标签: javascript jquery ajax asp.net-mvc asp.net-ajax