0

System.NullReferenceException is thrown everytime I try to insert the data into a database. I try to pass a model to a controller action, but obviously I send a null.

    [HttpGet]
    public ActionResult Answer(int step = -1, int techniqueId = -1)
    {

        StepsAnswersViewModel model = new StepsAnswersViewModel
        {
            Step = db.Steps
                .Where(x => x.TechniqueId == techniqueId & x.Order == step)
                .Select(x => x)
                .First()
        };

        ViewBag.step = step;
        ViewBag.tId = techniqueId;

        return View(model);
    }

    [HttpPost]
    public ActionResult Answer(StepsAnswersViewModel model)

Answer.chtml:

@model BachelorProject.Models.StepsAnswersViewModel

@{
  ViewBag.Title = "Answer";
 }

@Html.Partial("_Test", Model)

_Test.chtml:

@model BachelorProject.Models.StepsAnswersViewModel

@{
  ViewBag.Title = "Answer";
 }

<h2>Answer</h2>
@using (Html.BeginForm("Answer", "Home", 
             new { step = ViewBag.step + 1, echniqueId = 1 }, 
             FormMethod.Post))
{
  <label>@Model.Step.Text</label>
  @Model.Step.Id
  @Html.TextBoxFor(m => m.Text)
  <input type="submit" value="Next Step" />
}

When I click "Next Step", null is passed to the "Answer" action for a Post requests...

StepsAnswersViewModel:

public class StepsAnswersViewModel
{
    public Step Step { get; set; }
    public string Text { get; set; }
}
Konrad Gadzina
  • 3,277
  • 1
  • 15
  • 27
Shukhrat Raimov
  • 1,739
  • 4
  • 19
  • 26

1 Answers1

1

Try to replace your form fields with the following html helpers:

@html.LabelFor(model => model.Step.Text)
@Html.HiddenFor(model => model.Step.Id)
@Html.TextBoxFor(model => model.Text)

Then set a breakpoint in the Answer Post action, check the model parameters contents.

Ofiris
  • 5,727
  • 2
  • 32
  • 56
  • You very welcome, I encourage you to read more here: http://stackoverflow.com/questions/3866716/what-does-html-hiddenfor-do And a nice tutorial here: http://blog.michaelckennedy.net/2012/01/20/building-asp-net-mvc-forms-with-razor/ – Ofiris Feb 18 '14 at 20:02