为什么服务器端验证在带有实体框架的ASP.Net MVC3应用程序中不能正常工作? [英] Why isn't server side validation working in my ASP.Net MVC3 application with Entity Framework?

查看:64
本文介绍了为什么服务器端验证在带有实体框架的ASP.Net MVC3应用程序中不能正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET MVC3应用程序,该应用程序使用从数据库生成的实体.每个实体还具有一个单独的子类,该子类使用 MetadataType 属性将每个实体与一个装饰有许多验证属性的类相关联(见下文).

I have an ASP.NET MVC3 application that uses entities generated from a database. Each entity has also has a separate partial class that uses the MetadataType attribute to associate each entity with a class that is decorated with a number of validation attributes (see below).

[MetadataType(typeof(Drawing.Metadata))]
public partial class Drawing
{
    private sealed class Metadata
    {
        [Required]
        [StringLength(50, MinimumLength = 3, ErrorMessage = "Drawing numbers must be between {2} and {1} characters in length.")]
        [DisplayName("Drawing number")]
        public string Number { get; set; }

        [Required]
        [StringLength(255, MinimumLength = 3, ErrorMessage = "Drawing titles must be between {2} and {1} characters in length.")]
        public string Title { get; set; }
    }
}

我的控制器代码如下:

[HttpPost]
public ActionResult Create(Drawing drawing)
{
    if (ModelState.IsValid)
    {
        // Save to database here...
        return RedirectToAction("Index");
    }
    else
    {
        return View(drawing);
    }
}

我已经使用Visual Studio模板来创建用于添加,编辑和删除实体的视图(设计器代码尚未更改).

I have used the Visual Studio templates to create the views to add, edit and delete the entities (The designer code has not been altered).

我遇到的问题是,当我创建实体时,只有在启用了客户端验证的情况下,验证才有效.如果我关闭了客户端验证,那么 ModelState.IsValid 似乎总是返回true,并返回到索引页面.

The problem I am having is that when I create an entity, validation only works if I have client side validation enabled. If I turn off the client side validation then ModelState.IsValid always seems to return true and returns me to the index page.

任何人都可以提供有关如何使用Entity Framework实体进行服务器端验证的任何建议吗?

Can anyone provide any suggestions on how to get server side validation working with Entity Framework entities?

更新:

这个问题似乎与我的类似.这篇文章的作者似乎已经解决了问题,但无奈地省略了提及他们解决问题的方法 ...

It seems this question is similar to mine. The author of this post seems to have solved the problem but rather unhelpfully omitted to mention how they fixed the problem...

推荐答案

我找到了解决此问题的另一种方法.因为我真的不想将我的属性设置为可为空,所以我添加了以下内容:

I found another solution to this problem. Because I didn't really want to set my properties to nullable I added the following:

[DisplayFormat(ConvertEmptyStringToNull = false)]

在模型属性中添加以下注释也可以修复该错误.

Adding the following annotation to your model property fixes the error as well.

这篇关于为什么服务器端验证在带有实体框架的ASP.Net MVC3应用程序中不能正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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