本文介绍了" ID字段是必需的"上创建验证消息; ID没有设定为[必填]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用创建Asp.Net MVC 2风格的动作创建实体发生这种情况。

的POCO具有以下属性:

 公众诠释标识{获取;设置;}[需要]
公共字符串消息{搞定;组}

在创建实体的,ID是自动设置的,所以没有必要为它的创建行动。

该ModelState中说:ID字段是必需的,但我还没有设置如此。
有没有去的东西在这里自动?

编辑 - 原因揭密

究其原因,问题是由布拉德·威尔逊通过保罗斯佩兰扎在下面,他说(欢呼保罗)的评论人回答

EDIT - Update Model technique

I actually changed the way I did this again by using TryUpdateModel and the exclude parameter array asscoiated with that.

    [HttpPost]
    public ActionResult Add(Venue collection)
    {
        Venue venue = new Venue();
        if (TryUpdateModel(venue, null, null, new[] { "Id" }))
        {
            _service.Add(venue);
            return RedirectToAction("Index", "Manage");
        }
        return View(collection);
    }
解决方案

You can add the attribute:

 [Bind(Exclude = "Id")]

on the parameter in method rather than the class, that way on create you can exclude it and on edit it will still be mandatory:

public ActionResult Create([Bind(Exclude = "Id")] User u)
{
    // will exclude for create
}

public ActionResult Edit(User u)
{
    // will require for edit
}

这篇关于" ID字段是必需的"上创建验证消息; ID没有设定为[必填]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 18:48
查看更多