C# MVC4绑定多模型asp剃须刀

C# MVC4绑定多模型asp剃须刀,c#,asp.net,asp.net-mvc,asp.net-mvc-4,razor,C#,Asp.net,Asp.net Mvc,Asp.net Mvc 4,Razor,我开发了一个管理员工组成的应用程序,我使用MVC4 Asp.net和Razor 在我的模型中,我有两个类,它们是我数据库中的表和格式化程序培训师 在我的应用程序中,我可以创建一个“编队”,我想添加一个“编队”训练师列表,但我不知道我必须做什么。 我认为最好的解决方案是复选框列表,我成功地用foreach显示了我的复选框列表,但我不知道如何将选中复选框的结果传递到我的控制器 我看过很多教程,其中使用了“CheckBoxList”,我也尝试过使用,但我使用了一个ViewBag来填充它,他们没有解释如

我开发了一个管理员工组成的应用程序,我使用MVC4 Asp.net和Razor

在我的模型中,我有两个类,它们是我数据库中的表和格式化程序培训师

在我的应用程序中,我可以创建一个“编队”,我想添加一个“编队”训练师列表,但我不知道我必须做什么。 我认为最好的解决方案是复选框列表,我成功地用foreach显示了我的复选框列表,但我不知道如何将选中复选框的结果传递到我的控制器

我看过很多教程,其中使用了“CheckBoxList”,我也尝试过使用,但我使用了一个ViewBag来填充它,他们没有解释如何将它与ViewBag一起使用

现在我测试了一个带有两个按钮Add和Remove的双列表框,但这不起作用

所以,有人可以帮助我找到,并解释我必须如何做,好的或最好的解决方案

我为我的英语感到抱歉,我是一个法国女孩

我的一个解决方案如下所示: 我的控制器:

    public ActionResult Create()
    {     
        ViewBag.formateurListe = (from unFormateur in db.salarie
                                 where unFormateur.sFormateur == true
                                 select unFormateur).AsEnumerable()
.Select(m => new SelectListItem
                                 {
                                     Text = m.sNom.ToString() + " " + m.sPrenom.ToString(),
                                     Value = m.sId.ToString()
                                 }).ToList();

        return View();
    }

    [HttpPost]
    public ActionResult Create(formation formation, IEnumerable<SelectList> formateurList)
    {

        if (ModelState.IsValid)
        {
            db.formation.Add(formation);

            foreach (var unSal in formateurList)
            {
                formateur f = new formateur();
                f.ftIdFormation = formation.fId;
                f.ftIdSalarie = (int)unSal.SelectedValue;
                db.formateur.Add(f);

            }
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(formation);
    }

您是否尝试过使用viewmodel在视图中传递两个模型

例如:

视图模型

public class CreateFormationViewModel
{
    public Formation formation{ get; set; }
    public List<Formative> trainers {get;set;}

}
在你看来,你有:

@model [yournamespace].CreateFormationViewModel 

第一次使用复选框可能会很棘手——我在谷歌上搜索了很长时间

我的解决方案是一个视图模型,如下所示:

它用于提问,提问者可以通过复选框指定项目,例如,问题的答案可能有好的和坏的

public class QuestionModel
{
    public int QuestionID { get; set; }

    public string QuestionText { get; set; }

    /// <summary>
    /// Gets or sets the selected items. Purely a helper List to display check boxes for the user
    /// </summary>
    /// <value>
    /// The selected items.
    /// </value>
    [Display(Name = "Items", ResourceType = typeof(Domain.Resources.Question))]
    public IEnumerable<SelectListItem> SelectedItems { get; set; }

    /// <summary>
    /// Gets or sets the selected ids. Populated by the user, when he checks / unchecks items. Later translated into QuestionItems
    /// </summary>
    /// <value>
    /// The selected ids.
    /// </value>
    public int[] SelectedIds { get; set; }
}
这在QuestionController中按如下方式填充:

    private async Task GetSelectedItems(QuestionModel sm, Item selectedItems)
    {
        var alreadySelected = new List<Scale>();

        if (selectedScale != null)
        {
            alreadySelected.Add(selectedScale);
        }

        var itemList = (await this.uoW.ItemRepository.Get()).OrderBy(i => i.Name);

        sm.SelectedItems = itemList.Select(x => new SelectListItem
        {
            Value = x.ScaleID.ToString(),
            Text = x.NameOfScale.GetText(),
            Selected = (from a in alreadySelected where a.ItemID == x.ItemID select x).Any()
        });
    }
这有什么用?它获取数据库中所有可用项的列表,并用它填充模型。此外,您还可以传入已选中的项目列表,以便编辑现有问题并显示所有已选中的项目

在视图中,我使用了下拉列表:

    <div class="form-group">
        @Html.LabelFor(model => model.SelectedItems, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="checkbox">
                @Html.DropDownListFor(x => x.SelectedIds, Model.SelectedItems, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.SelectedItems, "", new { @class = "text-danger" })
            </div>
        </div>
    </div>
如果你想要复选框,这看起来像是另一个控制器,所以不要混淆

 for (int i = 0; i < Model.SelectedItems.Count(); i++)
        {
            var currentElem = Model.SelectedItems[i];
            //if this item is selected by the user, e.g. because he is editing the item, the item will be pre-selected
            var selected = currentElem.Selected ? "checked=\"selected\"" : string.Empty;

            // column for the questions. expected layout: list of all questions
            <div class="col-md-6">
                <div class="checkbox" id="SelectedIds">
                    <label>
                        <input type="checkbox" value="@currentElem.Value" @selected name="SelectedIds">
                        @Html.Encode(currentElem.Text)
                    </label>
                </div>
            </div>
        }
最后是create方法本身:

    [HttpPost]
            [ValidateAntiForgeryToken]
            public async Task<ActionResult> Create([Bind(Include = "QuestionText,SelectedItems, SelectedIds")] QuestionModel question)
            {
                if (ModelState.IsValid)
                {
// I need only one Item, but if you want ore more change this line
                    if (question.SelectedIds.Count() == 1)
                    {
// better use Automapper here, this is unnecessary work
                        var newQuestion = new Question { QuestionText = question.QuestionText};

                        var ItemID = question.SelectedIds.First();

                        newQuestion.QuestionScale = await this.uoW.ItemRepository.GetRaw().Where(i => i.ItemID == ItemD).FirstAsync();

                        this.uoW.QuestionRepository.Insert(newQuestion);

                        await this.uoW.Save();

                        return this.RedirectToAction("Index");
                    }
                    else
                    {
                        this.logger.Warn("User {0} tried to insert more than one Itemin question {1}", User.Identity.Name, question.QuestionID);
                        ModelState.AddModelError(string.Empty, xyz.Areas.QuestionManagement.Resources.QuestionRes.ErrorTooManyScales);
                    }
                }
                else
                {
// the SelectedItems are empty in the model - so if you have to redisplay it, repopulate it.
                    await this.GetSelectedItems(question, null);
                }

                return this.View(question);
            }

不,我不用它,我也不知道怎么用。。。这是我在ASPI的第一个项目。我有了更多的信息,这真的很像使用模型,但是你通常使用一些东西将你的模型映射到你的视图模型,比如Automapper。什么是你的FormationModel和你的TrainerModelAsList??很抱歉,我的问题对于开发人员来说可能很愚蠢,但我真的迷路了。谢谢你的回答我认为这个解释太短了,它没有解释任何关于模型的问题,因为它是一个确定的模型,你一定要创建这个模型来管理你的培训师数据列表,培训列表,如果你能给我们看一下你的代码就更好了…@Krishnajrana谢谢你
    <div class="form-group">
        @Html.LabelFor(model => model.SelectedItems, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="checkbox">
                @Html.DropDownListFor(x => x.SelectedIds, Model.SelectedItems, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.SelectedItems, "", new { @class = "text-danger" })
            </div>
        </div>
    </div>
 for (int i = 0; i < Model.SelectedItems.Count(); i++)
        {
            var currentElem = Model.SelectedItems[i];
            //if this item is selected by the user, e.g. because he is editing the item, the item will be pre-selected
            var selected = currentElem.Selected ? "checked=\"selected\"" : string.Empty;

            // column for the questions. expected layout: list of all questions
            <div class="col-md-6">
                <div class="checkbox" id="SelectedIds">
                    <label>
                        <input type="checkbox" value="@currentElem.Value" @selected name="SelectedIds">
                        @Html.Encode(currentElem.Text)
                    </label>
                </div>
            </div>
        }
    [HttpPost]
            [ValidateAntiForgeryToken]
            public async Task<ActionResult> Create([Bind(Include = "QuestionText,SelectedItems, SelectedIds")] QuestionModel question)
            {
                if (ModelState.IsValid)
                {
// I need only one Item, but if you want ore more change this line
                    if (question.SelectedIds.Count() == 1)
                    {
// better use Automapper here, this is unnecessary work
                        var newQuestion = new Question { QuestionText = question.QuestionText};

                        var ItemID = question.SelectedIds.First();

                        newQuestion.QuestionScale = await this.uoW.ItemRepository.GetRaw().Where(i => i.ItemID == ItemD).FirstAsync();

                        this.uoW.QuestionRepository.Insert(newQuestion);

                        await this.uoW.Save();

                        return this.RedirectToAction("Index");
                    }
                    else
                    {
                        this.logger.Warn("User {0} tried to insert more than one Itemin question {1}", User.Identity.Name, question.QuestionID);
                        ModelState.AddModelError(string.Empty, xyz.Areas.QuestionManagement.Resources.QuestionRes.ErrorTooManyScales);
                    }
                }
                else
                {
// the SelectedItems are empty in the model - so if you have to redisplay it, repopulate it.
                    await this.GetSelectedItems(question, null);
                }

                return this.View(question);
            }