Passing viewmodel to actionresult creates new viewmodel

Posted by Jonas Bohez on Stack Overflow See other posts from Stack Overflow or by Jonas Bohez
Published on 2012-07-01T15:12:43Z Indexed on 2012/07/01 15:15 UTC
Read the original article Hit count: 432

I am using a viewmodel, which i then when to send to an actionresult to use (the modified viewmodel)

But in the controller, i lose the list and objects in my viewmodel. This is my view:

@using PigeonFancier.Models
@model PigeonFancier.Models.InschrijvingModel
@using (Html.BeginForm("UpdateInschrijvingen","Melker",Model))
{
<div>
    <fieldset>
        <table>

            @foreach (var item in Model.inschrijvingLijst)
            {
                <tr>
                    <td>@Html.DisplayFor(model => item.Duif.Naam)</td>                              
                    <td> @Html.CheckBoxFor(model => item.isGeselecteerd)</td>                              
                </tr>
            }
        </table>   
        <input type="submit" value="Wijzigen"/>
    </fieldset>
</div>
}

This is my controller, which does nothing at the moment until i can get the full viewmodel back from the view.

public ActionResult UpdateInschrijvingen(InschrijvingModel inschrijvingsModel)

    {
        // inschrijvingsModel is not null, but it creates a new model before 
            it comes here with 
        //Use the model for some updates

        return RedirectToAction("Inschrijven", new { vluchtId = 
                   inschrijvingsModel.vlucht.VluchtId });
    }

This is the model with the List and some other objects who become null because it creates a new model when it comes back from the view to the actionresult

public class InschrijvingModel
{
    public Vlucht vlucht;
    public Duivenmelker duivenmelker;
    public List<CheckBoxModel> inschrijvingLijst { get; set; }

    public InschrijvingModel()
    {
        // Without this i get, No parameterless constructor defined exception. 
        // So it uses this when it comes back from the view to make a new model
    }

    public InschrijvingModel(Duivenmelker m, Vlucht vl)
    {
        inschrijvingLijst = new List<CheckBoxModel>();
            vlucht = vl;
            duivenmelker = m;

        foreach (var i in m.Duiven)

        {
            inschrijvingLijst.Add(new CheckBoxModel(){Duif = i, 
            isGeselecteerd =  i.IsIngeschrevenOpVlucht(vl)});
        }

    }

What is going wrong and how should i fix this problem please?

Thanks

© Stack Overflow or respective owner

Related posts about c#

Related posts about asp.net-mvc-3