我如何遵循此http://www.mikesdotnetting.com/Article/219/Saving-jQuery-Sortables-In-ASP.NET-Razor-Web-Pages如何将嵌套的可排序菜单保存在数据库中
我已经在Google中搜索过,但是没有帮助...我想知道什么是逻辑,以及如何使用嵌套菜单结构进行更新
-我的数据库结构
表1:菜单
[列] Menuid,MenuName,Parent,orderId
表2:MenuItems
[列]:Menuitemid,MenuitemName,Menuid(foreignkey),orderId
我的剃刀视图
<div>
<input type="button" id="getTech" style="width:100px;height:30px" value="Get Order" />
<div>
<ol class="example">
@if (ViewData["Menu"] != null)
{
foreach (var menu in ViewData["Menuitem"] as List<DB.Entities.MenuItem>)
{
<li class="item" id="@menu.MenuItemId">
@menu.MenuItemName
<ul></ul>
</li>
}
}
</ol>
</div>
</div>
<div class="row">
<div class="col-md-2">
<button>@Html.ActionLink("Save Order", "Index")"</button>
</div>
</div>
<script>
$(function () {
$("ol.example").sortable();
$('button').on('click', function() {
var ids = [];
$('.item').each(function(index, value) {
var id = $(value).prop('id');
ids.push(id);
});
$.post(
'/Sort',
{ Ids: JSON.stringify(ids) },
function(response) {
if ($('#message').hasClass('alert-info')) {
$('#message').text('Items re-ordered successfully.')
.removeClass('alert-info')
.addClass('alert-success');
} else {
$('#message').effect("highlight", {}, 2000);
}
}
);
});
})
我的控制器动作
public ActionResult Index()
{
try
{
string menu = (Request["ids"]);
var ids = new JavaScriptSerializer().DeserializeObject(menu) ;
}
catch (Exception ex)
{
}
return View();
}
最佳答案
以下是我在评论中建议的示例。
它不包括实际的菜单逻辑/插件,因为假定已经提供了该菜单逻辑/插件。您几乎需要逐步将其添加到新的MVC应用程序中。如果缺少任何内容,您只需要问。有时我会将其作为教程发布在我的网站上。
1. MenuItem类/表
您只需要一个表即可容纳菜单项和子菜单。唯一的区别是它们是否实际上有任何子项。菜单项只是ID和文本(如果需要,您可以添加超链接等)。
使用代码优先,我在此类中添加了MenuItems表:
public class MenuItem
{
// Unique id of menu item
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual int MenuItemId { get; set; }
// Tesxt to display on menu item
[Required]
public virtual string MenuItemName { get; set; }
// Sequential display order (within parent item)
public virtual int DisplayOrder { get; set; }
// Foreign key value
public virtual int? ParentMenuItemId { get; set; }
[ForeignKey("ParentMenuItemId")]
// Parent menu item
public virtual MenuItem ParentMenuItem { get; set; }
// Child menu items
public virtual ICollection<MenuItem> ChildItems { get; set; }
}
2.添加重新排序动作
这是实际重新排序商品的商品。通过页面上的Ajax使用
/menu/reorder/2?after=3
之类的URL进行调用,该URL将把项目ID 2移动到数据库中项目ID 3之后。在我的重新排序的第一个版本中,我曾经传递一个头寸,商品ID和父ID,但是由于复杂的父关系,在生产中发现的结果不如简单地说“您要移动哪个商品ID”有用, “您希望将其放置在哪个项目ID后面”(0表示首先放置它)。
/// <summary>
/// Reorder the passed element , so that it appears after the specific element
/// </summary>
/// <param name="id">Id of element to move</param>
/// <param name="after">Id of element to place after (or 0 to place first)</param>
/// <returns>Unused</returns>
public ContentResult Reorder( int id, int after )
{
var movedItem = this.context.MenuItem.Find(id);
// Find all the records that have the same parent as our moved item
var items = this.context.MenuItem.Where(x => x.ParentMenuItemId == movedItem.ParentMenuItemId).OrderBy(x => x.DisplayOrder);
// Where to insert the moved item
int insertionIndex = 1;
// Display order starts at 1
int displayOrder = 1;
// Iterate all the records in sequence, skip the insertion value and update the display order
foreach (var item in items)
{
// Skip the one to move as we will find it's position
if (item.MenuItemId != id)
{
// Update the position
item.DisplayOrder = displayOrder;
if (item.MenuItemId == after)
{
// Skip the insertion point for subsequent entries
displayOrder++;
// This is where we will insert the moved item
insertionIndex = displayOrder;
}
displayOrder++;
}
}
// Now update the moved item
movedItem.DisplayOrder = insertionIndex;
this.context.SaveChanges();
return Content(insertionIndex.ToString());
}
3.持有顶层菜单的视图
索引动作
//
// GET: /Menu/
public ActionResult Index()
{
// Return the top level menu item
var rootMenu = context.MenuItem.SingleOrDefault(x => x.ParentMenuItemId == null);
return View(rootMenu);
}
Index.cshtml
它包含用于通过Ajax调用进行可排序重新排序的代码。
@model jQuery.Vero.Menu.MvcApplication.Models.MenuItem
<h2>Test Menu gets rendered below</h2>
<ul id="menu" class="menu">
@foreach (var menuItem in Model.ChildItems.OrderBy(x=>x.DisplayOrder))
{
@Html.Action("Menu", new { id = menuItem.MenuItemId })
}
</ul>
@section scripts{
<script type="text/javascript">
$(function () {
var $menu = $("#menu");
// Connection menu plugin here
...
// Now connect sortable to the items
$menu.sortable({
update: function(event, ui)
{
var $item = $(ui.item);
var $itemBefore = $item.prev();
var afterId = 0;
if ($itemBefore.length)
{
afterId = $itemBefore.data('id');
}
var itemId = $item.data('id');
$item.addClass('busy');
$.ajax({
cache: false,
url: "/menu/reorder/" + itemId + "?after=" + afterId,
complete: function() {
$item.removeClass('busy');
}
});
}
});
});
</script>
}
4.递归局部视图
为了显示菜单项,我使用了递归操作和视图。
菜单动作
/// <summary>
/// Render one level of a menu. The view will call this action for each child making this render recursively.
/// </summary>
/// <returns></returns>
public ActionResult Menu(int id)
{
var items = context.MenuItem.Find(id);
return PartialView(items);
}
菜单部分视图-Menu.cshtml
@model jQuery.Vero.Menu.MvcApplication.Models.MenuItem
<li id="Menu@(Model.MenuItemId)" class="menuItem" data-id="@(Model.MenuItemId)">
@Model.MenuItemName
@if (Model.ChildItems.Any())
{
<ul class="menu">
@foreach (var menuItem in Model.ChildItems.OrderBy(x => x.DisplayOrder))
{
@Html.Action("Menu", new { id = menuItem.MenuItemId })
}
</ul>
}
</li>
5.其他样式
这些是我添加到测试应用程序中的唯一样式。注意我在删除的项目上添加和删除了一个
busy
类,以便在处理Ajax调用时它可以显示进度等。我在自己的应用中使用了进度微调器。.menu {
list-style: none;
}
.menu .menuItem{
border: 1px solid grey;
display: block;
}
.menu .menuItem.busy{
background-color: green;
}
6.样本数据
这是我输入的分层菜单项的示例(在下面生成屏幕截图)。
7.屏幕上的层次结构示例
这显示了以上代码呈现的层次结构。您可以将菜单插件应用于顶级UL。
关于c# - 如何在MVC 4 Razor 中的数据库中保存嵌套的可排序菜单?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23559052/