How to populate an array in side a model for postback

时间:2016-04-25 09:11:11

标签: c# asp.net arrays asp.net-mvc model

I have a model that contains a List of Milestone, I want that list to be populated (inside the model) with a given set of Textboxes in the webpage.

public class Project
{
    public string ProjectNumber { get; set; }
    public IList<Parameter> Parameters;
    public IList<Milestone> MilestoneList = new List<Milestone>();
}

And inside my Html.BeginForm("Edit", "Home", FormMethod.Post, new { Project = Model })) I have the following TextBox.

@for (int i = 0; i < Model.MilestoneList.Count; i++)
{  
    <td style="align-content: center;">@Html.TextBoxFor(model=>model.MilestoneList[i].Value)</td>
}

My problem in my controller below the milestonelist is always null in model Project

[HttpPost]
public ActionResult Edit(Project project)
{
    helper.CreateProject(project, System.Web.HttpContext.Current.User.Identity.Name);
    return View();
}

So how should I program so the list inside the model will be populated through TextBoxes?

1 个答案:

答案 0 :(得分:2)

Your using fields in the model, not properties, so the DefaultModelBinder cannot set the value. Change you model to

public class Project
{
    public string ProjectNumber { get; set; }
    public IList<Parameter> Parameters { get; set; }
    public IList<Milestone> MilestoneList { get; set; }
}

and initialize the collection in in the controller.