简体   繁体   English

用于在多对多关系 mvc 中创建 object 的输入类型无线电

[英]Input type radio for creating object in many-to-many relationship mvc

I have 3 models: Component, Category (categories of the components) and Sistem.我有 3 个模型:组件、类别(组件的类别)和系统。 I want to create a Sistem using already existing components.我想使用已经存在的组件创建一个系统。 In the create view I want to use radio input to select the Component, but it seems like the selected one doesn't go where it should.在创建视图中,我想使用无线电输入到 select 组件,但似乎所选的组件没有 go 应该在哪里。

I have two models that have a many-to-many relationship:我有两个具有多对多关系的模型:

public class Sistem
    {
        public Sistem()
        {
            this.Components = new HashSet<Component>();
        }
        public int Id { get; set; }
        public string Name { get; set; }                         
        public virtual ICollection<Component> Components { get; set; }   
    }

public class Component
    {
        public Component()
        {
            this.Sistems = new HashSet<Sistem>();
        }
        public int Id { get; set; }
        public int Name {get; set; }
        public ICollection<Sistem> Sistems { get; set; }
    }

public ActionResult Create()
        {
            Sistem sistem = new Sistem();
            var categories = from cat in db.Categories select cat;
            ViewBag.Categories = categories;
            sistem.Components = CreateAllComponents();
            return View(sistem);
        }

        public ActionResult Create(Sistem sistem)
        {

            var categories = from cat in db.Categories select cat;
            ViewBag.Categories = categories;
            if (ModelState.IsValid)
                {
                    db.Sisteme.Add(sistem);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            else
                {
                    return View(sistem);
                }
        }
        [NonAction]
        public ICollection<Component> CreateAllComponents()
        {
            Component empty = new Component();
            var listOfComponents = new List<Component>();
            var categories = from cat in db.Categories
                             select cat;
            foreach (var cat in categories)
            {
                listOfComponents.Add(empty);
            }
            return listOfComponents;
        }


Now I want to choose one Component from each Category and add it to the Sistem collection of Categories.现在我想从每个类别中选择一个组件并将其添加到类别的系统集合中。 This is in the View for Create:这是在创建视图中:

foreach (var cat in @ViewBag.Categories)
{
    int idx = 0;
    <div class="radio-toolbar">
        @foreach (var comp in cat.Components)
        {

                **<input type="radio" asp-for="@Model.Components.ToList()[idx]" id="@comp.Name"  name="@cat.Name" value="@comp"/>
                <label for="@comp.Name" asp-for="@Model.ComponenteSistem.ToList()[idx]"> @comp.Name</label>**
        }
    </div>
    idx = idx + 1;
}

It should link every component I choosed with the sistem that I'm currently creating but the relationship table ramains empty: enter image description here它应该将我选择的每个组件与我当前正在创建的系统链接,但关系表为空:在此处输入图像描述

I think the problem is this part from the label/input: asp-for="@Model.Components.ToList()[idx] but I don't know how to change it to make it work.我认为问题出在标签/输入的这一部分: asp-for="@Model.Components.ToList()[idx] 但我不知道如何更改它以使其工作。

Firstly,you cannot bind a whole model to radio button( value="@comp" ).Here is a working demo for binding Component Id and Name to Sistem: Category Model:首先,您不能将整个 model 绑定到单选按钮( value="@comp" )。这是一个将 Component Id 和 Name 绑定到 Sistem 的工作演示: Category Model:

public class Category {
        public List<Component> Components { get; set; }
    }

View(change checked radio button and the next hidden input name before form post,so that the selected Id and Name can be binded to Sistem.Components):查看(在表单发布前更改选中的单选按钮和下一个隐藏的输入名称,以便选择的Id和Name可以绑定到Sistem.Components):

<form id="myForm" method="post">
    @foreach (var cat in @ViewBag.Categories)
    {
    
    <div class="radio-toolbar">
        @foreach (var comp in cat.Components)
        {
        
            <input type="radio" id="@comp.Id" value="@comp.Id" />
            <input hidden id="compName_@comp.Id" value="@comp.Name" />
            <label for="@comp.Id"> @comp.Name</label>
        
            
        }
    </div>
    }
    <button>submit</button>
</form>
<script>
    $('#myForm').submit(function () {
        var count = 0;
        $(".radio-toolbar").each(function () {
            $(this).find("input[type='radio']:checked").attr("name", "Components[" + count + "].Id");
            $(this).find("input[type='radio']:checked").next().attr("name", "Components[" + count + "].Name");
            count++;
        })
        return true; // return false to cancel form action
    });
</script>

Controller(I use fake data to test):控制器(我用假数据来测试):

[HttpGet]
        public ActionResult Create()
        {
            Sistem sistem = new Sistem { 
                Id=1,
                Name="sistem1",
                Components=new List<Component> 
                {
                    new Component{ Id=11, Name=11},
                    new Component{ Id=12, Name=12},
                    new Component{ Id=13, Name=13}
                }
            };
            var categories = new List<Category> 
            {
                new Category{  Components=new List<Component>
                {
                new Component{ Id=11, Name=11},
                    new Component{ Id=12, Name=12},
                    new Component{ Id=13, Name=13}
                } },
                new Category{  Components=new List<Component>
                {
                new Component{ Id=21, Name=21},
                    new Component{ Id=22, Name=22},
                    new Component{ Id=23, Name=23}
                } },
                new Category{  Components=new List<Component>
                {
                new Component{ Id=31, Name=31},
                    new Component{ Id=32, Name=32},
                    new Component{ Id=33, Name=33}
                } }
            };
            ViewBag.Categories = categories;
            return View(sistem);
        }
        [HttpPost]
        public ActionResult Create(Sistem sistem)
        {
            return Ok();
        }

result:结果: 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM