c# - MVC3 - 发布时模型为空

标签 c# asp.net-mvc-3 razor

我有两个模型 - 类别和文章。我对它们都有几乎相同的删除 View 和 Controller 。唯一的区别是它适用于类别,但对于文章,我在 HttpPost 上得到空模型。

类别:

    public ActionResult DeleteCat(int id)
    {
        Category cat = db.CategoryByID(id);
        if (cat != null)
        {
            return View(cat);
        }

        return RedirectToAction("Index");
    }

    [HttpPost]
    public ActionResult DeleteCat(Category model)
    {
        db.DeleteCategory(model.CategoryID);

        return RedirectToAction("Index");
    }

文章:

    public ActionResult Delete(int id)
    {
        Article art = db.ArticleByID(id);
        if (art != null)
        {
            return View(art);
        }

        return RedirectToAction("Index");

    }

    [HttpPost]
    public ActionResult Delete(Article model)
    {
        db.DeleteArticle(model.ArticleID);

        return RedirectToAction("Index");
    }

这两个 View 都是由 Visual Studio 生成的,我没有更改它们。当我想删除一个类别时,一切顺利。但是当我想删除一篇文章时,它首先从数据库中正确选择,然后显示 View (一切正常)但是当我单击删除按钮时模型为空(所有属性为 0、null 或 false)并且所以 db.DeleteArticle 抛出异常(没有 ArticleID = 0 的文章)。任何人都可以就我应该检查什么或我应该如何解决这个问题向我提供任何提示吗?

最佳答案

如果 [HttpPost] 操作中模型的参数与模型中的属性同名,它将为 null 并且验证失败,表示该字段无效。

例子:

public class ContactMessage 
{
    public string Name { get; set; }
    public string sankdmfskm { get; set; }
}

[HttpPost]
public ActionResult Index(ContactMessage sankdmfskm)
{
...
}

sankdmfskm 将为 null

在 MVC3 和 MVC4 中测试。

关于c# - MVC3 - 发布时模型为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6206296/

相关文章:

c# - SynchronizationContext 有什么作用?

asp.net-mvc-3 - 为什么不大量使用 ViewBag?

c# - 如何在 asp.net core 中更改根路径 ~/in Razor

c# - 如何在 cshtml View 中使用 Asp .NET Core MVC 中的变量?

razor - ActionMailer.Net 独立 : There is no build provider registered for the extension '.cshtml'

c# - 使用网络响应加载网络浏览器

c# - 服务器上的全局自定义类

c# - 设置 JsonConvert.DefaultSettings asp net core 2.0 无法按预期工作

c# - 带有部分页面的客户端的 Outputcache 属性

jquery - 如何使用 Razor 在 javascript block 变量中使用 C# 变量?