几个问题... ModelState.IsValid 和分组复选框值
当我创建模型时使用 ASP.NET MVC,然后基于具有 CRUD 操作的模型的控制器,生成 CRUD 视图。我使用 Fluent API 添加了一些代码来要求某些字段,但由于某种原因,即使这些字段未完成,ModelState.IsValid 也会通过。是什么决定了这个通过与否?我认为它是基于您的模型属性数据类型和其他事物,例如必需的或最大长度等......
此外,我还手动添加了代码以从数据库中获取类别列表,并为其中的每个类别生成一个复选框看法。这是项目模型的导航属性,其中存在多对多关系。为了在控制器的 Create(Project project) 方法中获取一组已检查的值,我使用:
var selected = Request["categories"].Split(',');
但是,如果未检查任何值,则会抛出经典的“对象引用未设置为对象的实例”错误。所以我想知道的是,如何确定它没有任何值,以便一旦检测到我就可以做其他事情?
Using ASP.NET MVC when I create my model, then a controller based on the model with CRUD operations, the CRUD views are generated. I added some code using Fluent API to require certain fields but for some reason the ModelState.IsValid passes even when these fields are not completed. What determines whether this passes or not? I thought it was based on your model property data types and other things like being required or maxlength, etc....
Also, I have manually added code to grab a list of Categories from the database and generate a checkbox for each one in the View. This is a navigation property for the Project model where there is a many-many relationship. To get the group of checked values in the Create(Project project) method in the controller I use:
var selected = Request["categories"].Split(',');
This however, throws the classic Object reference not set to an instance of an object error if no values are checked. So what I want to know is, how can I determine that this does not have any values so I can do something else once detected?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ASP.NET MVC 不了解实体框架的 Fluent API,也不评估此配置。您只能使用MVC能够识别的数据注释:
不确定我的理解是否正确,但我想说:
ASP.NET MVC doesn't know anything about the Fluent API of Entity Framework and doesn't evaluate this configuration. You only can use the data annotations which MVC will recognize:
Not sure if I understand it correctly but I'd say: