SerenityNow
SerenityNow

Reputation: 1065

In MVC, posting of form return empty model

I have the following viewModel

 public class ExerciceViewModel
    {
        public string Code { get; set; }
        public string Titre { get; set; }
        public int QuestionCourante { get; set; }
    }

the following view

@model MonEcoleVirtuelle.ViewModel.ExerciceViewModel

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

<h2>Test</h2>

@using (Html.BeginForm("test", "exercice", FormMethod.Post))
{

    @Model.Code <br />

    @Model.Titre<br />

    @Model.QuestionCourante<br />
    <br />
    <br />

    Model.Code = "Code Modifie";

    <input type="submit" value="Post Moi Ca!" name="fini" />

}

and the following controller methods

 [HttpPost]
        public ActionResult Test(ViewModel.ExerciceViewModel model)
        {
            if (ModelState.IsValid)
            {
                return Content(model.Code);
            }

            return View(model);
        }

[HttpGet]
public ActionResult Test()
{
    var vm = new ViewModel.ExerciceViewModel { Code = "code1", Titre = "Mon titre", QuestionCourante = 1 };

    return View(vm);
}

When I submit the form, the model passed is empty, all properties are reset, not keeping the original values. What am I missing.

thanks

Upvotes: 3

Views: 6270

Answers (2)

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60493

well, instead of @Model.Code which just display the values, you need some inputs.

So @Html.TextBoxFor(m => m.Code) for example

To manage a collection, you can do something like that :

@for (var i = 0; i < Model.Collection.Count; i++) {
  Html.TextBoxFor(m => Model.Collection[i].Property)
}

Upvotes: 3

Kami
Kami

Reputation: 19407

You have not included any input fields in your view.

The @Model.Code etc only output the value of the field. To be able to post back elements they need to be form elements, like inputs. Use something like

@Html.TextBoxFor(p=>p.Code)

to create input fields that can then be posted back.

For a more complete guide see MSDN at http://msdn.microsoft.com/en-us/library/dd410596(v=vs.100).aspx

Upvotes: 3

Related Questions