ASP.Net MVC模型绑定我做错了什么
本文关键字:错了 什么 绑定 Net MVC 模型 ASP | 更新日期: 2023-09-27 17:49:14
当我试图访问发布的模型时,我得到了一个NullReference。我做错了什么?我已经试过了我能想到的所有方法,但我一定是错过了什么简单的东西?以下是我的相关代码:
控制器 public ActionResult EditQuestion(int id)
{
IFeedbackRepository rep = DAL.RepositoryFactory.GetFeedbackRepository();
var q = rep.GetQuestion(id);
SurveyQuestionEditModel question = new SurveyQuestionEditModel()
{
Id=q.Id,
IsFreeText=q.FreeTextResponse,
SurveyId=q.SurveyId,
Question=q.Question,
Category=q.Category
};
return View(question);
}
[HttpPost]
public ActionResult EditQuestion(SurveyQuestionEditModel question)
{
IFeedbackRepository rep = DAL.RepositoryFactory.GetFeedbackRepository();
rep.UpdateSurveyQuestion(question.Id, question.Question, question.IsFreeText, question.Category);
return RedirectToAction("Edit", new { id = question.SurveyId });
}
ASPX的相关部分:
<fieldset>
<%: Html.HiddenFor(model => model.Id) %>
<%: Html.HiddenFor(model => model.SurveyId) %>
<div class="editor-label">
<%: Html.LabelFor(model => model.Question) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Question) %>
创建:
<form action="/feedback/Survey/EditQuestion" method="post">
<fieldset>
<legend></legend>
<input id="Id" name="Id" type="hidden" value="72" />
<input id="SurveyId" name="SurveyId" type="hidden" value="4" />
<div class="editor-label">
<label for="Question">Question</label>
</div>
<div class="editor-field">
<input id="Question" name="Question" type="text" value="Test" />
</div>
<div class="editor-label">
<label for="Category">Question Category</label>
</div>
<div class="editor-field">
<input id="Category" name="Category" type="text" value="Test" />
</div>
<div class="editor-label">
<label for="IsFreeText">Does this question require a free text response?</label>
</div>
<div class="editor-field">
<input checked="checked" id="IsFreeText" name="IsFreeText" type="checkbox" value="true" /><input name="IsFreeText" type="hidden" value="false" />
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
</form>
下面是模型类:
public class SurveyQuestionEditModel
{
public int Id { get; set; }
[DisplayName("Question")]
[Required]
[MinLength(4)]
public string Question { get; set; }
[DisplayName("Does this question require a free text response?")]
public bool IsFreeText { get; set; }
public int SurveyId { get; set; }
[DisplayName("Question Category")]
[Required]
public string Category { get; set; }
}
看起来像这样的问题:当表单提交时,模型是null
替换你的参数名:
public ActionResult EditQuestion(SurveyQuestionEditModel question)