如何在mvc 4 razor中保存数据库中的嵌套可排序菜单?

时间:2014-05-09 07:36:49

标签: c# jquery asp.net-mvc asp.net-mvc-4 razor

如何在数据库中保存嵌套的可排序菜单我已遵循此http://www.mikesdotnetting.com/Article/219/Saving-jQuery-Sortables-In-ASP.NET-Razor-Web-Pages

我在谷歌搜索但没有帮助...我想知道什么是逻辑以及我如何用嵌套菜单结构更新

- 我的数据库结构

表1:的菜单
[Columns] Menuid,MenuName,Parent,orderId
表2:的的MenuItems
[[column]: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();
}

1 个答案:

答案 0 :(得分:5)

下面是我在评论中建议的一个例子。

它不包括实际的菜单逻辑/插件,因为假设已经提供了它。几乎所有您需要逐步添加到新的MVC应用程序。如果它缺少任何东西你只需要问。我会在某个时候在我的网站上发布这个教程。

1。 MenuItem类/表

您只需要一个表来保存菜单项和子菜单。唯一的区别是他们是否真的有任何儿童用品。菜单项只是id和文本(如果需要,可以添加超链接等)。

使用Code-first我在这个类中添加了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调用,它会将项目ID 2移动到数据库中的项目ID 3之后。

在我的重新排序的第一个版本中,我曾经传递过一个位置,项目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。样本数据

这是我输入的分层菜单项的示例(在下面生成屏幕截图)。

enter image description here

7。层次结构的屏幕示例

这显示了上面代码呈现的层次结构。您可以将菜单插件应用到顶级UL。

enter image description here