[英]HttpPost returns null Model in ASP.NET MVC
提前警告,我對 ASP.NET 非常陌生。
我正在開發一個項目,該項目將顯示 db 表中的數據行。 當用戶單擊行旁邊的“忽略”按鈕時,它應該在數據庫中將該行上相應的“忽略”列更新為true
。
視圖本身工作正常,它按預期顯示所有數據。 But when "Ignore" is clicked, and it calls the Ignore() method on the controller, the model is which is passed to the controller is null.
我的 model,由實體框架生成(刪除了無關屬性):
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace IgnoreDailyItems.Models
{
[Table("DataChecks.tbl.DailyItems")]
public partial class DataChecksTblDailyItems
{
[Column("entryId")]
public int EntryId { get; set; }
[Column("ignore")]
public bool? Ignore { get; set; }
}
}
風景:
@model IEnumerable<IgnoreDailyItems.Models.DataChecksTblDailyItems>
@{
ViewBag.Title = "Placeholder";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.EntryId)
</th>
</tr>
@{ var item = Model.ToList(); }
@for(int i = 0; i < Model.Count(); i++)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item[i].EntryId)
</td>
<td>
@using (Html.BeginForm("Ignore", "Home", FormMethod.Post))
{
@Html.HiddenFor(modelItem => item[i].EntryId)
<button type="submit" class="btn btn-danger">Ignore</button>
}
</td>
</tr>
}
</table>
controller 上的 Ignore() 方法:
[HttpPost]
public ActionResult Ignore(DataChecksTblDailyItems modelData)
{
using (var context = new IgnoreDailyItemsContext())
{
var query = context.DataChecksTblDailyItems
.Where(b => b.EntryId.Equals(modelData.EntryId));
foreach (var q in query)
{
q.Ignore = true;
}
context.SaveChanges();
return RedirectToAction("Index", "Home");
}
}
您需要將IEnumerable<IEnumerable>
作為參數傳遞。
public ActionResult Ignore(IEnumerable<DataChecksTblDailyItems> modelData)
{
您以錯誤的方式生成表單。
@Html.HiddenFor(modelItem => item[i].EntryId)
它將生成一個隱藏的輸入item[0].EntryId
, item[1].EntryId
... 作為表中每一行的名稱/id,因此 model 后定義不匹配。
要解決它,請手動設置輸入隱藏名稱:
@Html.Hidden("EntryId", item[i].EntryId)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.