Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC: Can I use ModelState inside class out of controller?

Tags:

c#

asp.net-mvc

Can I do this inside one class?

    ...
    using System.Web.Mvc;
    ...

    public static class aaa 
    {

      public static test() {

         if (something) ModelState.AddModelError("", "test");
      }

    }

inside controller call:

...

public class MyControler {

     public void Index() {
          ....
          aaa.test();
          ....
     }

}

Is it possible? I want to control the code inside a classes in another part of the controller.

like image 685
David Avatar asked Jun 06 '14 11:06

David


People also ask

How does ModelState work in MVC?

When MVC creates the model state for the submitted properties, it also iterates through each property in the view model and validates the property using attributes associated to it. If any errors are found, they are added to the Errors collection in the property's ModelState .

How ModelState IsValid works in MVC?

ModelState. IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process. In your example, the model that is being bound is of class type Encaissement .


2 Answers

You can pass your model state around like this:

public static void test(ModelStateDictionary ModelState)
{
    if (something) ModelState.AddModelError("", "test");
}

And call from inside your controller:

aaa.test(ModelState);
like image 97
DavidG Avatar answered Sep 29 '22 12:09

DavidG


No, you can't. What you're referencing inside Controller is its property, not a class. You can still pass it to the method being called as an argument.

like image 26
Serg Rogovtsev Avatar answered Sep 29 '22 14:09

Serg Rogovtsev