首页 > 解决方案 > 远程验证 Json MVC

问题描述

在提交表单之前,我需要验证用户的输入字段值。我在自定义控制器中创建了一个动作,并用 Month 装饰了该字段。

[Required]
        [DataType(DataType.Date)]
        //[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:Y}")]
        [DisplayFormat(DataFormatString = "{0:dd/MMM/yyyy}")]
        [Display(Name = "Month")]
        [Remote("IsvalidMonth", "Objectives", AdditionalFields = "UserID,SalesObjectiveID", ErrorMessage = "Month already existing")]
        //[DisplayFormat(DataFormatString = "{0:MMM-yyyy}")]
        public Nullable<System.DateTime> Month { get; set; }    

我的验证是:

public JsonResult IsvalidMonth(DateTime Month, int? SalesObjectiveID, int? UserID)
        {
            var monthexist = _context.TBL_SalesObjective.Where(x => x.Month == Month && x.SalesObjectiveID == SalesObjectiveID && x.UserID == UserID).FirstOrDefault().Month;

            return Json(!monthexist, JsonRequestBehavior.AllowGet);
        }

但我不能使用 !monthexist 因为运营商!不能应用。

如何在 Monht 中进行验证?

标签: asp.net-mvc

解决方案


这 '!' 运算符可以与布尔值一起使用,因为你正在做.FirstOrDefault().Month的不是布尔值,所以你不能使用'!' 操作员。

IsvalidMonth()请在您的方法中尝试以下代码

var monthexist = _context.TBL_SalesObjective.Any(x => x.Month == Month && x.SalesObjectiveID == SalesObjectiveID && x.UserID == UserID);

推荐阅读