开发者

MVC 3 Webapp - Model Binder

开发者 https://www.devze.com 2023-03-25 12:09 出处:网络
I am creating my first MVC app and one of the pages need to list a series of questions from a table in a database. I have set-up the Model:

I am creating my first MVC app and one of the pages need to list a series of questions from a table in a database. I have set-up the Model:

public class Audit
{
    public DateTime InspectionDate { get; set; }
    public string Engineer { get; set; }
    public List<AuditGroup> AuditGroups { get; set; }
}

public class AuditGroup
{
    public string GroupName { get; set; }
    public List<AuditQuestion> AuditQuestions { get; set; }
}

public class AuditQuestion
{
    public string Group { get; set; }
    public string Question { get; set; }
    public string Answer { get; set; }
    public string Comments { get; set; }
}

The models contains Lists, I created a page called Create and populated the model with the groups and questions in the groups and these displayed on the page fine. When I answer the questions (fill in a textbox) and press the submit button it calls the controller:

    [HttpPost]
    public ActionResult Create(Audit newAudit)
    {
        try
        {
            // TODO: Add insert logic here

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

开发者_StackOverflowThe newAudit has data in the Engineer and Inspection Date but the binder is not picking up the Lists on the page. This is a cut down version I have trying to work it out:

@{
    ViewBag.Title = "Audit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@model test.Models.Audit
<h2>
    Audit</h2>
@using (Html.BeginForm())
{
<fieldset>

    @foreach (var AuditGroups in Model.AuditGroups)
    { 
     @Html.EditorFor(x=> AuditGroups.GroupName)

        }
</fieldset>
<p>
    <input type="submit" value="Create" />
</p>

}

So here I am going through the list and putting them on the page but on submit the list is null. Does anyone know where I am going wrong?

In summary what I am doing is sending a list of question to page, user to fill in and submit the answers but im not getting the answers for any of the Lists.


please have a look at my answer to this question. it contains some blog posts that addressed this issue. Furthermore, read Yarx's comment on the answer in which he provided the link to a post which helped him solve the problem.

0

精彩评论

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