繁体   English   中英

HttpPost 在 ASP.NET MVC 中返回 null Model

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM