在 .net MVC 中创建多对多关系的视图

发布于 2024-12-25 15:03:56 字数 2670 浏览 4 评论 0原文

我正在 MVC 中创建一个 MediaLibrary。 我有一个“MediaType”模型和一个“Support”模型。 每个媒体类型(电影、游戏、音乐)都可以有 n 个支持(CD、DVD、蓝光……)。

我创建了模型并添加了关系(hasmany,withmany,...),支持的控制器和视图(这里没有问题),但我现在不知道如何管理 MediaType 的控制器和视图,以便能够添加多个支撑并使用模型验证它们。

MediaType 模型:

[Bind(Exclude = "MediaTypeId")]
public class MediaType
{
    [ScaffoldColumn(false)]
    public int MediaTypeId { get; set; }

    [DisplayName("Media type")]
    public string name { get; set; }

    // Disponible supports
    public virtual ICollection<Support> Supports { get; set; }
}

支持模型

[Bind(Exclude = "SupportId")]
public class Support
{
    [ScaffoldColumn(false)]
    public int SupportId { get; set; }

    [DisplayName("Support name")]
    public string name { get; set; }

    // MediaTypes using this support (not used in the view now)
    public virtual ICollection<MediaType> MediaTypes { get; set; }
}

MediaType 控制器的创建操作

public ActionResult Create()
    {
        ViewData["SupportsList"] = new SelectList(db.Supports.ToList(), "SupportId", "name");
        return View();
    } 
[HttpPost]
    public ActionResult Create(MediaType mediatype)
    {
        if (ModelState.IsValid)
        {
            db.MediaTypes.Add(mediatype);
            db.SaveChanges();
            return RedirectToAction("Index");  
        }

        ViewData["SupportsList"] = new SelectList(db.Supports.ToList(), "SupportId", "name");
        return View(mediatype);

MediaType 控制器的创建操作的创建视图(支持部分)

<div class="editor-field" id="supportList">
        @Html.DropDownList("Supports", (SelectList)ViewData["SupportsList"])
        <a href="#" id="addSupport">Ajouter</a>&nbsp;<span id="addSupportError" class="error"></span>
        <script type="text/javascript">
            $('#addSupport').click(function () {
                if ($('input[name="SupportsIds[]"][value="' + $('#Supports').val() + '"]').length < 1) {
                    $('#supportList').append('<div>' + $('#Supports option:selected').text() + '<input type="hidden" name="SupportsIds[]" value="' + $('#Supports').val() + '" /></div>');
                    $('span#addSupportError').text('');
                } else {
                    $('span#addSupportError').text('The support has already been added');
                }
            });
        </script>
    </div>

我实际上在 jQuery 中做了一个奇怪的脚本来将支持添加到 MediaType,有一个包含数据库中所有支持的下拉列表,当您单击添加时,它会添加一个带有名称的标签和一个带有支持 ID 的隐藏字段(隐藏字段名称为“SupportIds[]”,因此它应该返回一个支持列表ids,不?)

有人已经编码了这样的东西(多对多,...)?

I'm creating a MediaLibrary in MVC.
I have a "MediaType" Model and a "Support" model.
Each MediaType (Film, Game, Music) can have n Support (CD, DVD, BluRay,...).

I created the models and added the relations (hasmany, withmany,...), the controller and views for Support (no problem here), but I don't now how to manage the controller and view for the MediaType, to be able to add multiple Supports and to validate them with the model.

The MediaType model :

[Bind(Exclude = "MediaTypeId")]
public class MediaType
{
    [ScaffoldColumn(false)]
    public int MediaTypeId { get; set; }

    [DisplayName("Media type")]
    public string name { get; set; }

    // Disponible supports
    public virtual ICollection<Support> Supports { get; set; }
}

The Support model

[Bind(Exclude = "SupportId")]
public class Support
{
    [ScaffoldColumn(false)]
    public int SupportId { get; set; }

    [DisplayName("Support name")]
    public string name { get; set; }

    // MediaTypes using this support (not used in the view now)
    public virtual ICollection<MediaType> MediaTypes { get; set; }
}

The Create action from the MediaType controller

public ActionResult Create()
    {
        ViewData["SupportsList"] = new SelectList(db.Supports.ToList(), "SupportId", "name");
        return View();
    } 
[HttpPost]
    public ActionResult Create(MediaType mediatype)
    {
        if (ModelState.IsValid)
        {
            db.MediaTypes.Add(mediatype);
            db.SaveChanges();
            return RedirectToAction("Index");  
        }

        ViewData["SupportsList"] = new SelectList(db.Supports.ToList(), "SupportId", "name");
        return View(mediatype);

The Create view for the Create action of the MediaType controller (the part for the Supports)

<div class="editor-field" id="supportList">
        @Html.DropDownList("Supports", (SelectList)ViewData["SupportsList"])
        <a href="#" id="addSupport">Ajouter</a> <span id="addSupportError" class="error"></span>
        <script type="text/javascript">
            $('#addSupport').click(function () {
                if ($('input[name="SupportsIds[]"][value="' + $('#Supports').val() + '"]').length < 1) {
                    $('#supportList').append('<div>' + $('#Supports option:selected').text() + '<input type="hidden" name="SupportsIds[]" value="' + $('#Supports').val() + '" /></div>');
                    $('span#addSupportError').text('');
                } else {
                    $('span#addSupportError').text('The support has already been added');
                }
            });
        </script>
    </div>

I actually did a weird script in jQuery to add Supports to the MediaType, there is a dropdown list with all supports in db, when you click add, it adds a label with the name and a hidden field with the id of the support (the hiddens fields names are "SupportIds[]" so it should return a List of support ids, no ?)

Did someone already coded something like this (many-to-many,...) ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文