简体   繁体   中英

In an MVC4 controller action, how can I validate a model only when it's passed in?

I have a class as such..

public class TestClass
{
    [DataMember(IsRequired = true)]
    [Required]
    public string Test { get; set; }
    [DataMember(IsRequired = true)]
    [Required]
    public string Test2 { get; set; }
}

I'm basically trying to achieve this with my controller action..

public ActionResult Index(string value1, string value2, TestClass testClass)
{
    if (testClass != null && !ModelState.IsValid)
    {
        //return validation errors
    }
    //continue processing

However due to MVC model binding, TestClass is not null and therefore it's instantiated containing null properties for the strings Test and Test2 , which in turn forces it to check the ModelState.IsValid which is of course false.

Can someone point out where I'm going wrong or suggest a better alternative?

EDIT.

I'm checking for a null because the requirement is that value1 and value2 have to be passed into the system, then the TestClass contains extra information on what is being supplied. The extra information isn't required, however it is supplied it needs to be validated.

I think the only solution is to use custom model binding (implement IModelBinder ).

This gives you full access over the deserialization of the object.

See this article on SO and Figure 7 from MSDN :

Or maybe you can get in between using an action filter (see section Handling Validation Errors).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM