ASP.NET Post请求异常:Edit方法参数始终为null的解决问询
解决ASP.NET MVC中Edit方法参数为null的问题
看起来你遇到的核心问题是Model绑定失败,导致提交表单时SmallTalkAnswer参数始终为null。结合你的代码,我帮你梳理一下问题根源和修复步骤:
问题根源:只读属性的Model绑定冲突
你的SmallTalkAnswer继承自TableEntity,其中Timestamp属性是只读的(Azure Storage SDK中TableEntity.Timestamp的setter是internal,外部无法赋值)。但自动生成的视图里却包含了Timestamp的编辑输入框,当表单提交时,Model绑定器尝试为这个只读属性赋值,失败后会直接放弃整个对象的绑定,最终导致answer参数为null。
另外,ETag虽然通常有public setter,但它是用于乐观并发控制的,不需要用户手动编辑,也不应该放在可编辑的输入框中。
修复步骤
1. 修改视图,移除只读/不需要编辑的字段
打开你的Edit视图,删除Timestamp和ETag的编辑区块(如果需要保留ETag用于并发控制,可以改成隐藏字段):
修改后的视图核心部分:
@model ChatBotAdminCenter.Models.SmallTalkAnswer @{ ViewBag.Title = "Edit"; } <h2>Edit</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>SmallTalkAnswer</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.PartitionKey, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.PartitionKey, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.PartitionKey, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.RowKey, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.RowKey, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.RowKey, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Answer, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Answer, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Answer, "", new { @class = "text-danger" }) </div> </div> <!-- 如果需要ETag做并发控制,添加隐藏字段 --> @Html.HiddenFor(model => model.ETag) <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Save" class="btn btn-default" /> </div> </div> </div> } <div> @Html.ActionLink("Back to List", "Index") </div>
2. 优化控制器的Edit方法,添加ModelState校验
在控制器中先校验ModelState是否有效,如果无效返回视图并显示错误,方便排查后续问题:
[HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(SmallTalkAnswer answer) { // 先检查ModelState是否有效 if (!ModelState.IsValid) { // 如果无效,返回视图并显示错误信息 return View(answer); } _smallTalkAnswerRepository.Update(answer); return RedirectToAction("Index"); }
3. 确保Repository的Update方法正确处理TableEntity
如果你的Update方法是操作Azure Table Storage,需要正确传入ETag来支持乐观并发:
public void Update(SmallTalkAnswer answer) { // 示例:使用Azure.Data.Tables的TableClient _tableClient.UpdateEntityAsync(answer, answer.ETag, TableUpdateMode.Replace).Wait(); }
验证修复
做完以上修改后,重新运行项目,提交编辑表单,answer参数应该能正常获取到表单提交的值,之后就能正常写入数据库了。
内容的提问来源于stack exchange,提问作者mahu
相关产品推荐
相关产品推荐

