开发者

referencing a list<Model> in a looping ParialView

I have been trying to loop partial views, which share the same model as the main view. Basically the idea is that there is a registration page where a parent can register multiple children, the children info is in partial view so that i can add multiple instances of it on the main view.

I can get the partial view to display multiple times but it only saves the first student. if i replace the partial view (@Html.Partial...) with @Html.EditorFor(f => f.student[i].Person.FirstName) in the main view then it works fine and i can add multiple textboxes and save multiple students

how can i use the partial views and be able to pass in the ParentModel and correctly reference it?

hope all this makes sense... any help is appreciated. thanks!

Model:

public partial class Person()
{
    public string Fi开发者_C百科rstName { get; set; }
}

public partial class Student
{
    public int Student_PersonID { get; set; }
    public int Father_PersonID { get; set; }

    public virtual Person Father { get; set; }
    public virtual Person Person { get; set; }
 }

public class ParentModel
{
    public List<Student> student { get; set; }
}

Main View

@model WebPortal.Models.ParentModel

<div>
   @for (int i = 0; i < cnt; i++)
   {
       @Html.Partial("_StudentPartial", Model, new ViewDataDictionary { { "loopIndex", i.ToString() } });
   }
</div>
<div>
      @Html.EditorFor(f => f.student[0].Father.FirstName)
</div>

Partial View (_StudentPartial)

@model WebPortal.Models.ParentModel
@{
     int i = Convert.ToInt32(ViewData["loopIndex"].ToString());
 }
@using (Html.BeginForm())
{
       <div class="editor-field">
           @Html.EditorFor(m => m.student[i].Person.FirstName)
       </div>
}

Controller

public ActionResult Register(ParentModel pm)
{
   using (var db = new SMEntities())
   {
      for (int i = 0; i < pm.student.Count; i++)
      {
         if (i != 0)
         {
            pm.student[i].Father = pm.student[0].Father;
         }

         db.Students.Add(pm.student[i]);
      }

      db.SaveChanges();
   }
}


A better way to structure things will be like this :

Type the _StudentPartial View to Student like this -

@model WebPortal.Models.Student
@using (Html.BeginForm())
{
       <div class="editor-field">
           @Html.EditorFor(m => m.Person.FirstName)
       </div>
}

Then model your main view like this :

@model WebPortal.Models.ParentModel

<div>
   @for (int i = 0; i < cnt; i++)
   {
       @Html.Partial("_StudentPartial", Model.student[i]);
   }
</div>
<div>
      @Html.EditorFor(f => f.student[0].Father.FirstName)
</div>

Try to use this as a guideline : Give to the view only the information it needs, not more.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜