Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Model view controller asp.net mvc中的验证属性_Model View Controller_Asp.net Mvc 3_Attributes_Custom Attributes - Fatal编程技术网

Model view controller asp.net mvc中的验证属性

Model view controller asp.net mvc中的验证属性,model-view-controller,asp.net-mvc-3,attributes,custom-attributes,Model View Controller,Asp.net Mvc 3,Attributes,Custom Attributes,我的模型是这样的: public class Line { public int CatalogNumber {get; set;} public int TeamCode {get; set;} } 我有一个获取目录号和团队代码的视图,我想检查两件事: 我们的数据库中有这样的目录号 给定团队有这样的目录号 我编写了一个属性(源自ValidationAttribute),用于检查数据库中是否有这样的目录号。但它什么也没做 也许不可能用属性进行这样的检查 (我知道我可以实现IVa

我的模型是这样的:

public class Line
{
    public int CatalogNumber {get; set;}
    public int TeamCode {get; set;}
}
我有一个获取目录号和团队代码的视图,我想检查两件事:

  • 我们的数据库中有这样的目录号
  • 给定团队有这样的目录号
  • 我编写了一个属性(源自
    ValidationAttribute
    ),用于检查数据库中是否有这样的目录号。但它什么也没做

    也许不可能用属性进行这样的检查

    (我知道我可以实现
    IValidable
    和重写
    IsValid
    方法,但出于我自己的原因,我更喜欢使用属性来实现)

    我必须在没有serverPost的情况下完成它(ajax会很好)

    我真的很欣赏一个很好的例子


    p、 (我们正在使用mvc3)

    我认为远程验证可以帮助您解决这个问题。您可以使用它检查数据库中是否存在目录号:

    public class Line
    {
        [Remote("QueryCatalogNumberExists", "Home")]
        public int CatalogNumber { get; set; }
        public int TeamCode { get; set; }
    }
    
    然后在您的控制器中(我还没有测试过这段代码,但它应该是类似的):

    我相信您还可以有其他字段,以便检查目录号对于给定的团队代码是否有效(我认为团队代码必须为空,因为用户在当前模型中输入目录号之前可能无法输入,因为团队代码不是必需的)。所以你的模型是:

    public class Line
    {
        [Remote("QueryCatalogNumberExistsForTeamCode", "Home", AdditionalFields = "TeamCode")]
        public int CatalogNumber { get; set; }
        public int TeamCode { get; set; }
    }
    
    以及控制器代码:

    public JsonResult QueryCatalogNumberExistsForTeamCode(int catalogNumber, int? teamCode)
    {
        if (_repository.QueryCatalogNumberExistsForTeamCode(catalogNumber, teamCode))
        {
            return Json(true, JsonRequestBehavior.AllowGet);
        }
        return Json(false, JsonRequestBehavior.AllowGet); 
    }
    

    我希望这能为您指明解决问题的正确方向。

    哇,这是一个非常好的答案!我现在就去试试。
    public JsonResult QueryCatalogNumberExistsForTeamCode(int catalogNumber, int? teamCode)
    {
        if (_repository.QueryCatalogNumberExistsForTeamCode(catalogNumber, teamCode))
        {
            return Json(true, JsonRequestBehavior.AllowGet);
        }
        return Json(false, JsonRequestBehavior.AllowGet); 
    }