开发者

Validation attribute in asp.net mvc

开发者 https://www.devze.com 2023-02-22 05:42 出处:网络
My model is something like this: public class Line { public int CatalogNumber {get; set;} public int TeamCode {get; set;}

My model is something like this:

public class Line
{
    public int CatalogNumber {get; set;}
    public int TeamCode {get; set;}
}

I have a view that gets catalog number and a team code, And I want to check two things:

  1. there is such catalog number in our database
  2. There is such catalog number for the given team

I开发者_开发知识库 wrote an attribute (that derives from ValidationAttribute) that checks if there is such a catalog number in our Data Base. But it does nothing!

Maybe it's impossible to such check with an attribute?

(I know that I can implement IValidable and override IsValid method but for my own reasons I prefer doing it with an attribue).

I've to do it without serverPost (ajax would be good)

I'll really appreciate a good example hot to do it.

p.s. (We are using mvc3)


I think that Remote Validation could help you out with this problem. You could use it to check that the catalog number exists in the database:

public class Line
{
    [Remote("QueryCatalogNumberExists", "Home")]
    public int CatalogNumber { get; set; }
    public int TeamCode { get; set; }
}

Then in your controller (I haven't tested this code but it should be something along the lines of):

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

I believe you can also have additional fields so that you could check that the catalog number is valid for the given TeamCode (I think the TeamCode would have to be nullable as the user may not enter one before entering a catalog number in your current model as the team code is not required). So your model would be:

public class Line
{
    [Remote("QueryCatalogNumberExistsForTeamCode", "Home", AdditionalFields = "TeamCode")]
    public int CatalogNumber { get; set; }
    public int TeamCode { get; set; }
}

and the controller code:

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

I hope this points you in the right direction to a solution.

0

精彩评论

暂无评论...
验证码 换一张
取 消