2014-07-11 64 views
0

我开发一个管理员工队伍的应用程序,我用Razor使用MVC4 Asp.net。MVC 4绑定多个模型asp剃须刀

在我的模型中,我有两个班级(谁是我的数据库中的表格)和业余(培训人员)。

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

我看到很多使用“CheckBoxList”的教程,我也尝试使用,但是我使用ViewBag来填充它,但他们没有解释如何将它与viewbag一起使用。

现在我测试一个双列表框与两个按钮(添加和删除),但这是行不通的。

那么,有人可以帮助我找到并解释我必须怎么做,好的或最好的解决方案?

我很抱歉我的英语,我是一个法国女孩。

我的一个解决方案是这样的: 我的控制器:

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

笔者认为:

@model MvcAppGestionRH.Models.formation 
@using (Html.BeginForm("Create", "Formation", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    @Html.ValidationSummary(true) 

      @Html.Label("Libelle")   
      @Html.EditorFor(model => model.fLibelle) 
      @Html.ValidationMessageFor(model => model.fLibelle) 

       <label id="fFormateur">Formateur</label>         

       @Html.ListBox("formateurListe", ViewData["formateurListe"] as SelectListItem[], new {Multiple = "multiple"}) 

       <input type="button" value="+" name="add" /> 
       <select name="select" size="7" > 
       </select>  
<input type="submit" value="Créer" />   
} 

随着脚本:

$(function() { 
      $("#Add").click(function() { 
       $("select").add($('fFormateurListe').selected); 
      }); 
     }); 
+0

最好是,如果你能告诉我们你的代码... –

回答

-1

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

例如:

视图模型

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

} 

,然后使用这个视图模型在你看来

一个简单的方法来使用此视图模式:

在你的控制器

public ActionResult CreateFormation() 
{ 
    //Get your data (formation and trainer) 
    CreateFormationViewModel createFormationVM = new CreateFormationViewModel(); 
    createFormationVM.formation = YourFormationModel; 
    createFormationVM.trainers = YourtrainersModelasList; 

    //bind data to the view 
    return View(createFormationVM); 
} 

而且在您看来,您有:

@model [yournamespace].CreateFormationViewModel 
+0

不,我不使用它并且我不知道如何使用......这是我在ASP中的第一个项目 –

+0

我已经获得了更多信息,它实际上就像使用模型一样,但通常使用一些东西将模型映射到像Automapper这样的视图模型。 – JDahm

+0

什么是“YourFormationModel”和“YourtrainersModelasList”?我很抱歉,我的问题对于开发者来说可能是愚蠢的,但我真的迷失了。感谢您的回答 –

1

复选框可能会非常棘手的第一次 - 我用Google搜索,长期以来,太。

我的解决方案是一个视图模型看起来像这样:

其目的是为问题,其中crator可以通过speciy复选框的项目(如一个问题可能会回答“好”与“坏”。

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

这是什么呢?它获取数据库中所有可扩展项目的列表,并使用它填充模型。此外,您可以传入已经选择的项目列表 - 因此您可以编辑现有的问题,并扫描所有已检查的项目。

和n我用一个DropDownList的观点:

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

+1很好地解释了...... –

+0

@KrishnrajRana谢谢 –