2014-02-18 444 views
0

System.NullReferenceException每次嘗試將數據插入數據庫時​​都會引發。 我嘗試將模型傳遞給控制器​​操作,但顯然我發送了空值。如何將模型傳遞到視圖

[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請求...

StepsAnswersViewModel:

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

你能顯示'StepsAnswersViewModel'的定義嗎? – Ofiris

+0

當然,剛剛添加 –

+0

'步'有'ID'和'文字'字段? – Ofiris

回答

1

嘗試使用下面的HTML傭工取代你的表單字段:

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

然後在Answer POST操作設置斷點,檢查model參數內容。

+0

它工作!:)非常感謝你! –

+0

你非常歡迎,我鼓勵你在這裏閱讀更多: http://stackoverflow.com/questions/3866716/what-does-html-hiddenfor-do 這裏有一個很好的教程:http://blog.michaelckennedy。 net/2012/01/20/building-asp-net-mvc-forms-with-razor/ – Ofiris

+0

好的,謝謝你的鏈接! –