0

I am passing a list of model in the View page and only editing the Answer property of the model. But after postback all the properties are set to null except Answer property.

Here is the View Code.

@model List<NewsLetter.Models.NewsLetterQuestions>           
@using (Html.BeginForm())
{
  @Html.AntiForgeryToken()

  for (var i = 0; i < Model.Count(); i++)
    {        
      <div>
        @Html.DisplayFor(m => m[i].Question)
      </div>

      <div>
         @Html.EditorFor(m => m[i].Answer)
      </div>   
}
      <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
          <input type="submit" value="Submit" class="btn btn-default" />
        </div>
      </div>    
}

Any help will be appreciable.

Kevin Andrid
  • 1,795
  • 1
  • 13
  • 25
Simba
  • 747
  • 6
  • 25

2 Answers2

2

That is how the model binding is supposed to work. It will create NewsLetterQuestions objects and set the properties your form send to the controller action. See Introduction to ASP.NET MVC Model Binding for an explanation with examples.

If you need to post additional model data from your view to the controller you can use Html.HiddenFor(model => model.SomeProperty). See What does Html.HiddenFor do? for an explanation.

Community
  • 1
  • 1
user2900970
  • 701
  • 1
  • 4
  • 18
  • I am glad to hear that. I highly recommend reading the first article if you are unfamiliar with model binding. It explains the basics quite well and in brief. – user2900970 Feb 19 '16 at 07:30
1

The DisplayFor() does not returns anything. You could use the below code.

@model List<NewsLetter.Models.NewsLetterQuestions>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    for (var i = 0; i < Model.Count(); i++)
    {
        <div>
            @Html.TextBoxFor(m => m[i].Question, new {@readonly = "readonly"})
        </div>

        <div>
            @Html.EditorFor(m => m[i].Answer)
        </div>

    }
       <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Submit" class="btn btn-default" />
            </div>
        </div>

}

Hope this helps

anand
  • 1,417
  • 3
  • 18
  • 39