gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:55:34 26 4
gpt4 key购买 nike

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

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

-我的数据库结构

表1:菜单
[列] Menuid、MenuName、Parent、orderId
表2:菜单项
[列]:Menuitemid、MenuitemName、Menuid(外键)、orderId

我的 Razor View

<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);
}
}
);
});
})

我的 Controller 操作

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 来调用的,这会将数据库中的项目 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);
}

索引.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。递归部分 View

为了显示菜单项,我使用递归操作和 View 。

菜单操作

    /// <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);
}

菜单部分 View - 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

关于c# - 如何在 mvc 4 razor 的数据库中保存嵌套的可排序菜单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23559052/

26 4 0