如何将模型传递给视图

时间:2014-02-18 19:48:14

标签: entity-framework asp.net-mvc-4

每当我尝试将数据插入数据库时​​,都会抛出

System.NullReferenceException。 我尝试将模型传递给控制器​​动作,但显然我发送了一个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" />
}

当我点击“下一步”时,null会传递给Post请求的“Answer”操作......

StepsAnswersViewModel:

public class StepsAnswersViewModel
{
    public Step Step { get; set; }
    public string Text { get; set; }
}

1 个答案:

答案 0 :(得分:1)

尝试使用以下html帮助程序替换表单字段:

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

然后在Answer发布操作中设置断点,检查model参数内容。