开发者

Model Validation problem in ASP.NEt MVC 2 RC 2

I have facing the following problem after the update.

I have a Model with Class level Validation plus property level validation in it. After updating to MVC 2 RC 2. The model validation fails on Model binding. What i actually understand that new mechanism trying to validate the model when you first request it or say on GET and it get null object exception during tryvalidatemodel Model binding call.

My Model is like this below

[Serializable]    
[MetadataType(typeof(InterestClaimMetaData))] //metadata with all properties level validation

//these validations fails when you request a page.
[DateComparison("DateA", "DateB", eDateComparitor.GreaterThan, 
    ErrorMessage = "Date A must be greater than B Date")]

[MutuallyExclusive("A", "B", ErrorMessage = "Please select either A or B field")]   

public class IE {
    public i开发者_运维技巧nt ID { get; set; }
    public byte[] Updated { get; set; }
}

DataComparison and MutuallyExclusive overrides the validate function isvalid and check the validation but it fails trying to validate as first requested. dont know how to stop this happening as it should not validate model on get request; just attach the properties.

Only models without these class level validation works.

Please advise. Thanks


Seperate your action method in your controller in to two action methods. Mark one as GET and the other as POST. Then only apply the validation in the POST method. So, for example, if you currently have an method called Create that looks something like this...

public ActionResult Create(YourModel yourModel)
{
    // Some code in here to validate stuff
    // Some code in here to do stuff
    return RedirectToAction("Index");
}

Split this out in to two methods like this...

[HttpGet]
public ActionResult Create()
{
    return View();
} 

[HttpPost]
public ActionResult Create(YourModel yourModel)
{
    try
    {
        // Some code in here to validate stuff
        // Some code in here to do stuff
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜