为什么要为int,long值设置MVC Model Binder集? [英] Why MVC Model Binder set required for int, long values?

查看:69
本文介绍了为什么要为int,long值设置MVC Model Binder集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的模型

public int Id {get;set;}

[Required]
public string FirstName{get; set}
[Required]
public string LastName{get; set}

该ID在数据库中自动生成.当我想调用Create action时,ModelState说"Id字段是必需的" !!!我发现 解决我的问题,但这不是干净的解决方案. 还有其他解决方法吗?

The Id is auto generate in DB. when I want call Create action The ModelState says that "The Id field is required"!!!! I Found this for my problem but it not clean solution. Is there an other way to solve this?

是否可以更改值类型的Mvc ModelBinder行为?

Is there a way that I change Mvc ModelBinder behavior for value types?

推荐答案

此问题的最佳解决方案是使用视图模型.视图模型是您专门设计用来满足视图要求的类.因此,您的控制器操作将采用此视图模型作为参数.只需停止将域模型传递给视图即可.就是这样.

The best solution to this problem is to use a view model. A view model is a class that you specifically design to meet the requirements of your view. So your controller action will take this view model as parameter. Simply stop passing your domain models to your views. That's it.

如果您不想遵循良好做法并使用视图模型,则可以通过在Application_Start中添加以下内容来禁用此隐式验证:

And if you don't want to follow good practices and use view models you could disable this implicit validation by adding the following to your Application_Start:

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

另一个 hack 是使用[Bind(Exclude = "Id")]属性将该属性排除在绑定之外.是的,这是骇客行为,但如果您不遵循良好做法,则必须忍受骇客行为.

another hack is to exclude this property from binding using the [Bind(Exclude = "Id")] attribute. Yeah, it's a hack but if you don't follow good practices you will have to live with hacks.

这篇关于为什么要为int,long值设置MVC Model Binder集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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