" ID字段是必需的"上创建验证消息; ID没有设定为[必填] [英] "The Id field is required" validation message on Create; Id not set to [Required]

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

问题描述

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

的POCO具有以下属性:

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

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

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

编辑 - 原因揭密

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


  

您要提供一个值
  ID,你只是不知道你是。
  这是默认的路由数据
  路线({控制器} / {行动} / {ID}),
  其默认值是空
  字符串,它是无效的int。
  使用[绑定]属性上的
  操作参数排除ID。我的
  默认路由是:新{控制器=
  客户,行动=编辑,ID =
  } //参数的默认值


编辑 - 更新模型技术

其实,我用TryUpdateModel并与asscoiated排除参数数组改变了我再次这样做的方式。

  [HttpPost]
    公众的ActionResult添加(地点集合)
    {
        场馆场地=新馆();
        如果(TryUpdateModel(场地,NULL,NULL,新的[] {ID}))
        {
            _service.Add(场地);
            返回RedirectToAction(指数,管理);
        }
        返回查看(集合);
    }


解决方案

您可以添加属性:

  [绑定(不包括=ID)]

在方法而不是类​​的参数,这样就创建您可以排除它和编辑它仍然是必需的:

 公众的ActionResult创建([绑定(不包括=ID)用户u)
{
    //将排除创建
}公众的ActionResult编辑(用户u)
{
    //将需要编辑
}

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

The POCO has the following properties:

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.

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?

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):

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

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没有设定为[必填]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆