Armel Mercier
Armel Mercier

Reputation: 1

ASP.NET MVC view return empty object

I have the following code, but it return me an empty FormationDTO object, did I do anything wrong?
I don't understand why it can't properly bind FormationFormViewModel's FormationDTO to the action parameter FormationDTO, it worked in others controllers.

FormationsController

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Save(FormationDTO formation)
{
    if (!ModelState.IsValid){
        return View("FormationForm", new FormationFormViewModel { FormationDTO = formation, Categories = GetCategories() });
    }
    else{
        // DO THE STUFF
    }

}

FormationForm.cshtml

@model BSS_IT_Education.Models.FormationFormViewModel

@{ 
    ViewBag.Title = "Formation";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@using (Html.BeginForm("Save", "Formations"))
{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(model => model.FormationDTO.Id)

    <div class="form-horizontal">

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.FormationDTO.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-4">
                @Html.EditorFor(model => model.FormationDTO.Name, new { htmlAttributes = new { @class = "form-control", @placeholder = "Entrez le nom de la formation..." } })
                @Html.ValidationMessageFor(model => model.FormationDTO.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        // BUNCH OF OTHERS FORM-GROUPS

        <div class="form-group">
            <div class="col-md-offset-2 col-md-8">
                <button type="submit" class="btn btn-success">@((Model.FormationDTO.Id == 0) ? "Sauvegarder  " : "Modifier")</button>                
            </div>
        </div>
    </div>
}

Upvotes: 0

Views: 979

Answers (2)

Jonesopolis
Jonesopolis

Reputation: 25370

Take a look at the generated HTML on the page. I'm guessing the name attributes on your input elements will look something like formationDTO.name, because your ViewModel is a FormationFormViewModel. But the ModelBinder on the backend is going to look for just a property name, because you are trying to build a FormationDTO.

You may need to manually create those input elements, or use a child action to get the correct ViewModel to a view that lets you use the razor @Html helpers to build the correct elements.

Or, the easier option is to make your controller action accept a FormationFormViewModel, then the ModelBinder should correctly build out the properties of the FormationDTO you want.

Upvotes: 0

JamesS
JamesS

Reputation: 2300

If I am understanding the code correctly. It looks like you should be passing FormationFormViewModel to the controller action. Not FormationDTO.

Upvotes: 1

Related Questions