asp.net-mvc Create 上的“Id 字段是必需的”验证消息;Id 未设置为 [必需]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2142990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:06:04  来源:igfitidea点击:

"The Id field is required" validation message on Create; Id not set to [Required]

asp.net-mvcasp.net-mvc-2data-annotations

提问by Dan

This is happening when I try to create the entity using a Create style action in Asp.Net MVC 2.

当我尝试在 Asp.Net MVC 2 中使用 Create 样式操作创建实体时,就会发生这种情况。

The POCO has the following properties:

POCO 具有以下属性:

public int Id {get;set;}

[Required]
public string Message {get; set}

On the creation of the entity, the Id is set automatically, so there is no need for it on the Create action.

在创建实体时,会自动设置 Id,因此在 Create 操作中不需要它。

The ModelState says that "The Id field is required", but I haven't set that to be so. Is there something automatic going on here?

ModelState 说“Id 字段是必需的”,但我没有将其设置为如此。这里有什么自动发生的吗?

EDIT - Reason Revealed

编辑 - 原因揭晓

The reason for the issue is answered by Brad Wilson via Paul Speranza in one of the comments below where he says (cheers Paul):

Brad Wilson 通过 Paul Speranza 在下面的评论之一中回答了这个问题的原因,他说(为 Paul 加油):

You're providing a value for ID, you just didn't know you were. It's in the route data of the default route ("{controller}/{action}/{id}"), and its default value is the empty string, which isn't valid for an int. Use the [Bind] attribute on your action parameter to exclude ID. My default route was: new { controller = "Customer", action = "Edit", id = " " } // Parameter defaults

你为 ID 提供了一个值,你只是不知道你是。它在默认路由(“{controller}/{action}/{id}”)的路由数据中,它的默认值为空字符串,对int无效。在您的操作参数上使用 [Bind] 属性来排除 ID。我的默认路由是: new { controller = "Customer", action = "Edit", 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.

我实际上通过使用 TryUpdateModel 和与之相关的排除参数数组再次改变了我这样做的方式。

    [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);
    }

回答by Rosstified

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
}

回答by Ulises

I ran into this issue with a form in which I was adding "objects" to a list dynamically. Therefore, our users were able to add, remove or update. It all worked well except for the cases when new items were created. For this reason, in my case, excluding the Id property was not an option. The solution was to make the ID Nullable:

我在一个表单中遇到了这个问题,我在其中动态地将“对象”添加到列表中。因此,我们的用户能够添加、删除或更新。除了创建新项目的情况外,一切都运行良好。出于这个原因,就我而言,排除 Id 属性不是一个选项解决方案是使 ID Nullable

public int? Id { get; set; }

This way existing items will have a value and new ones will have null instead. Good stuff.

这样,现有项目将有一个值,而新项目将改为 null。好东西。

回答by Andrei R?nea

Great question and answers, saved my ... behind. I need to add something, though:

很棒的问题和答案,拯救了我的......落后。不过,我需要添加一些内容:

Instead of

代替

[Bind(Exclude = "Id")]

I think it's better to use

我认为最好使用

[Bind(Include = "Prop1, Prop2, Prop3, etc")]

.. where Prop1, Prop2 and Prop3 are THE ONLYproperties that you want to be bound at the action level.

.. 其中 Prop1、Prop2 和 Prop3 是您希望在操作级别绑定的唯一属性。

Since this is white-listing as opposed to black-listing. White-listing is better, safer. This way you also solve the risk of over posting and under posting too. See Brad Wilson's post.

因为这是白名单而不是黑名单。白名单更好,更安全。通过这种方式,您还可以解决过度发布和发布不足的风险。参见Brad Wilson 的帖子

回答by Barbaros Alp

[Bind(Exclude = "Id")]
public class Hebe
{
      public int Id {get;set;}

      [Required]
      public string Message {get; set}
}

By the way above it doesnt bind the Id Property for your model on create

通过上面的方式,它不会在创建时为您的模型绑定 Id 属性

回答by user1911353

The Id should be sent from the client as 0. The model does not have a problem with Id=0, this is the default of int. The problem is that he does not see the value coming from the client or it's coming with space or null. I have an input hidden that represents the Id (or in complex object NestedPropertyId/NestedProperty.Id) so I make sure it starts with a value of zero.

从客户端发送的Id应该是0。模型没有问题,Id=0,这是int的默认值。问题是他没有看到来自客户端的值,或者它带有空格或空值。我有一个表示 Id 的隐藏输入(或在复杂对象 NestedPropertyId/NestedProperty.Id 中),因此我确保它以零值开头。

<input type="hidden" id="id" value="0" />
<input type="hidden" id="eventId" value="0"/>
<input type="hidden" id="contactId" value="0"/>

Also when Ireset the form to Add New entity in the client side, I make sure to initialize the hidden with zero.

此外,当我将表单设置为在客户端添加新实体时,我确保用零初始化隐藏。

Hope this helps somone.

希望这有助于某人。

Efy

艾菲

回答by Than Aramburo

Check in your view. Remove if your have hiddenfieldfor id field. This is used only for editing. @Html.HiddenFor(Model => Model.Id)

检查您的视图。如果您有 hiddenfieldfor id 字段,请删除。这仅用于编辑。@Html.HiddenFor(Model => Model.Id)

回答by andreydruz

add ? to int

添加 ?到 int

[Key]
[HiddenInput(DisplayValue = false)]
public int? ID { get; set; }

回答by Paul Speranza

I have the same problem, using RC2 with a POCO. If you name a property Id but do not put an validation attributes on it but IsValid says it is required. If I name a property anything but Id this does not happen. Why should I have to Exclude Id?

我有同样的问题,将 RC2 与 POCO 一起使用。如果您命名一个属性 Id 但没有在其上放置验证属性,但 IsValid 表示它是必需的。如果我将属性命名为 Id 以外的任何内容,则不会发生这种情况。为什么我必须排除 Id?

Thanks

谢谢

回答by mnemosyn

I just created a new MVC2 project, and added a simple POCO as well as a Controller and a View. From what I understand, you're using model binding to create the object, that is

我刚刚创建了一个新的 MVC2 项目,并添加了一个简单的 POCO 以及一个控制器和一个视图。据我了解,您正在使用模型绑定来创建对象,即

using System.ComponentModel.DataAnnotations;
public class SimpleObject
{
    public int Id {get;set;}
    [Required]
    public string Message { get; set; }
}

in the Controller we have

在控制器中,我们有

[HttpPost]
public ActionResult Create(SimpleObject created)
{
    /// do something
}

and in the View, there is no editor for the ID field?

而在视图中,ID 字段没有编辑器?

This should not end up in any error messages. Instead, the Id is supposed to be set to default(int) which is 0. This works for me. What version of MVC2 are you using (the RC I assume)?

这不应以任何错误消息结束。相反,Id 应该设置为 default(int),即 0。这对我有用。您使用的是什么版本的 MVC2(我假设是 RC)?

Don't get me wrong: It is important to prevent the Id from being bound by the model binders since that would allow an attacker to tamper with the Id of the object. Nonetheless, the default model binder should not show the behaviour you describe.

不要误会我的意思:防止 Id 被模型绑定器绑定很重要,因为这将允许攻击者篡改对象的 Id。尽管如此,默认模型绑定器不应显示您描述的行为。

回答by PBG

In my case, the problem was coming from the fact that ID was of a type string. Changing to an int(not nullable) fixed it for me. The stringtype was a result of reverse engineering a badly designed database.

在我的情况下,问题来自 ID 的类型为string。更改为int(不可为空的)为我修复了它。该string类型是对设计不良的数据库进行逆向工程的结果。