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

查看:168
本文介绍了为什么不是服务器端验证我的实体框架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; }
    }
}

我的控制器code是这样的:

My controller code looks like this:

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

我已经使用了Visual Studio的模板来创建视图来添加,编辑,删除实体(设计师code一直没有改变)。

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.

任何人都可以提供关于如何让服务器端验证实体框架实体的工作有什么建议?

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天全站免登陆