在MVC2的NerdDinner表单验证DataAnnotations错误当一个表单字段为空 [英] NerdDinner form validation DataAnnotations ERROR in MVC2 when a form field is left blank

查看:187
本文介绍了在MVC2的NerdDinner表单验证DataAnnotations错误当一个表单字段为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

平台: Windows 7旗舰版的结果
IDE:的Visual Studio 2010旗舰版的结果
网络环境: ASP.NET MVC 2 的结果
数据库: SQL Server 2008 R2的防爆preSS 的结果
数据访问:实体框架4 的结果
表单验证: DataAnnotations 的结果
示例应​​用程序:从Wrox的临ASP.NET MVC 2的NerdDinner 的结果
图书: Wrox的专业MVC 2 的结果
问题第1章 - 部分: (第33〜35)用模型类集成验证和业务规则逻辑

Platform: Windows 7 Ultimate
IDE: Visual Studio 2010 Ultimate
Web Environment: ASP.NET MVC 2
Database: SQL Server 2008 R2 Express
Data Access: Entity Framework 4
Form Validation: DataAnnotations
Sample App: NerdDinner from Wrox Pro ASP.NET MVC 2
Book: Wrox Professional MVC 2
Problem with Chapter 1 - Section: "Integrating Validation and Business Rule Logic with Model Classes" (pages 33 to 35)

错误简介:的NerdDinner形式验证错误与DataAnnotations和db空值。

ERROR Synopsis: NerdDinner form validation ERROR with DataAnnotations and db nulls.

在数据库字段设置为不允许空样品code DataAnnotations不起作用。

DataAnnotations in sample code does not work when the database fields are set to not allow nulls.

错误与书,并与codePLEX下载示例code中的code发生。

ERROR occurs with the code from the book and with the sample code downloaded from codeplex.

帮助!我真的这个沮丧!我不能相信这么简单的东西只是不工作???

Help! I'm really frustrated by this!! I can't believe something so simple just doesn't work???

重现步骤ERROR:


  1. 设置数据库字段不允许NULL (见图片)

  2. 设置NerdDinnerEntityModel晚餐类字段
    可为空属性设置为false (见图片)

  3. 添加DataAnnotations为Dinner_Validation类的(code A)

  4. 创建晚宴库类的(code B)

  5. 添加创建动作DinnerController (code C)

  6. 这是空白窗体,然后再发布的(见图片)

  7. 张贴时出现此空ERROR
    空白表格应该是
    由Dinner_Validation类截获
    DataAnnotations。的注意错误消息
    说:这个属性不能
    设置为空值。 WTH ???
    (见图片)

  8. 下一个错误在编辑过程中发生
    处理。这里是在编辑控制器
    行动(code D)

  9. 这是编辑的形式与故意错
    输入测试验证晚餐
    DataAnnotations (见图片)

  10. 张贴当错误再次发生
     编辑表格空白表单域。 POST请求
     应该由Dinner_Validation类DataAnnotations被截​​获。相同
     空输入错误。 WTH? (见图片)

  1. Set Database fields to not allow NULLs (See Picture)
  2. Set NerdDinnerEntityModel Dinner class fields' Nullable property to false (See Picture)
  3. Add DataAnnotations for Dinner_Validation class (CODE A)
  4. Create Dinner repository class (CODE B)
  5. Add CREATE action to DinnerController (CODE C)
  6. This is blank form before posting (See Picture)
  7. This null ERROR occurs when posting a blank form which should be intercepted by the Dinner_Validation class DataAnnotations. Note ERROR message says that "This property cannot be set to a null value. WTH??? (See Picture)
  8. The next ERROR occurs during the edit process. Here is the Edit controller action (CODE D)
  9. This is the "Edit" form with intentionally wrong input to test Dinner Validation DataAnnotations (See Picture)
  10. The ERROR occurs again when posting the edit form with blank form fields. The post request should be intercepted by the Dinner_Validation class DataAnnotations. Same null entry error. WTH??? (See Picture)

查看屏幕截图,时间:

See screen shots at:

http://www.intermedia4web.com/temp/nerdDinner/StackOverflowNerdDinnerQuestionshort.png

code答:

CODE A:

    [MetadataType(typeof(Dinner_Validation))]
    public partial class Dinner { }

    [Bind(Include = "Title, EventDate, Description, Address, Country, ContactPhone, Latitude, Longitude")] 
    public class Dinner_Validation
    {
        [Required(ErrorMessage = "Title is required")]
        [StringLength(50, ErrorMessage = "Title may not be longer than 50 characters")]
        public string Title { get; set; }

        [Required(ErrorMessage = "Description is required")]
        [StringLength(265, ErrorMessage = "Description must be 256 characters or less")]
        public string Description { get; set; }

        [Required(ErrorMessage="Event date is required")]
        public DateTime EventDate { get; set; }

        [Required(ErrorMessage = "Address is required")]
        public string Address { get; set; }

        [Required(ErrorMessage = "Country is required")]
        public string Country { get; set; }

        [Required(ErrorMessage = "Contact phone is required")]
        public string ContactPhone { get; set; }

        [Required(ErrorMessage = "Latitude is required")]
        public double Latitude { get; set; }

        [Required(ErrorMessage = "Longitude is required")]
        public double Longitude { get; set; }
    }

code B:

CODE B:

    public class DinnerRepository
    {
        private NerdDinnerEntities _NerdDinnerEntity = new NerdDinnerEntities();

        // Query Method
        public IQueryable<Dinner> FindAllDinners()
        {
            return _NerdDinnerEntity.Dinners;
        }

        // Query Method
        public IQueryable<Dinner> FindUpcomingDinners()
        {
            return from dinner in _NerdDinnerEntity.Dinners
                   where dinner.EventDate > DateTime.Now
                   orderby dinner.EventDate
                   select dinner;
        }

        // Query Method
        public Dinner GetDinner(int id)
        {
            return _NerdDinnerEntity.Dinners.FirstOrDefault(d => d.DinnerID == id);

        }

        // Insert Method
        public void Add(Dinner dinner)
        {
            _NerdDinnerEntity.Dinners.AddObject(dinner);
        }

        // Delete Method
        public void Delete(Dinner dinner)
        {
            foreach (var rsvp in dinner.RSVPs)
            {
                _NerdDinnerEntity.RSVPs.DeleteObject(rsvp);
            }

            _NerdDinnerEntity.Dinners.DeleteObject(dinner);
        }

        // Persistence Method
        public void Save()
        {
            _NerdDinnerEntity.SaveChanges();
        }
    }

code C:

CODE C:

        // **************************************
        // GET: /Dinners/Create/
        // **************************************
        public ActionResult Create()
        {
            Dinner dinner = new Dinner() { EventDate = DateTime.Now.AddDays(7) };
            return View(dinner);
        }

        // **************************************
        // POST: /Dinners/Create/
        // **************************************
        [HttpPost]
        public ActionResult Create(Dinner dinner) {
            if (ModelState.IsValid) 
            {               
                dinner.HostedBy = "The Code Dude";
                _dinnerRepository.Add(dinner);
                _dinnerRepository.Save();
                return RedirectToAction("Details", new { id = dinner.DinnerID });
            }
            else
            {
                return View(dinner);   
            }
        }

code D:

CODE D:

        // **************************************
        // GET: /Dinners/Edit/{id}
        // **************************************
        public ActionResult Edit(int id)
        {
            Dinner dinner = _dinnerRepository.GetDinner(id);
            return View(dinner);
        }

        // **************************************
        // POST: /Dinners/Edit/{id}
        // **************************************
        [HttpPost]
        public ActionResult Edit(int id, FormCollection formValues)
        {
            Dinner dinner = _dinnerRepository.GetDinner(id);
            if (TryUpdateModel(dinner)){
                _dinnerRepository.Save();
                return RedirectToAction("Details", new { id=dinner.DinnerID });
            }
            return View(dinner);
        }

我已经派人和Wrox的作者之一请求帮助,但还没有听说过任何人回来。这本书的读者甚至无法继续完成,因为这些错误的1章的其余部分。即使我从codePLEX下载最新版本,它仍然有同样的错误。是否有人可以帮助我,告诉我需要修正什么呢?谢谢 - 编者

I have sent Wrox and one of the authors a request for help but have not heard back from anyone. Readers of the book cannot even continue to finish the rest of chapter 1 because of these errors. Even if I download the latest build from Codeplex, it still has the same errors. Can someone please help me and tell me what needs to be fixed? Thanks - Ed.

推荐答案

工具 - >选项 - >(扩大)调试 - >(一般)启用异常助手

Tools -> Options -> (expand) Debugging -> (General) Enable the exception assistant.

这只是Visual Studio的努力是有帮助的! :)吓死我太先......以为有一个与code的东西展示-stoppingly错了。叶氏,只是恢复执行,所有将被罚款。验证内部将捕获的异常(这和其他人也,如转换,范围等),并在ModelState.Errors收集记录它。

It's just Visual Studio trying to be helpful! :) Scared me too at first ... thought there was something show-stoppingly wrong with the code. Yeap, just resume execution and all will be fine. The validation internals will catch the Exception (this and others as well, such as conversion, range, etc) and log it in the ModelState.Errors collection.

这篇关于在MVC2的NerdDinner表单验证DataAnnotations错误当一个表单字段为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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