user3205479
user3205479

Reputation: 1523

How do I check if a class is a model class in MVC

I started learning ASP.NET MVC and I have got some doubt. How do I check if a class is a Model class in MVC. I have PHP Codeigniter background, where all models inherit CI_Model. It was easy to figure out whether a class is a model class or not by checking instanceof operator but in .NET MVC Model class do not extend any class.

So how do I figure out whether a class is a model class through C# Code? How does MVC framework figure out whether the class is model or not. I have renamed folder from "Models" to "Modelss" but still model binding works with ModelState.IsValid. Any help is greatly appreciated.

Upvotes: 0

Views: 639

Answers (1)

R. Richards
R. Richards

Reputation: 25161

Most models in an MVC application are plain old CLR objects (POCOs), that often don't have a base class because it isn't needed. You can change that, if you need to.

In the following examples, lets assume you have a object called param coming in from somewhere.

In C#, you can check if an object is of a certain type in a few ways. You can cast the object to the type, and if you don’t get an exception, the cast was successful. This is not the preferred method any longer, but I wanted you to know if was an option.

try {
    var myType = (MyModel)param; // cast happens here
    // do something with myType
}
catch{
    // cast failed
}

Another way is to use the as operator. This is a much better way to do this because no exception is thrown if the cast fails, you just get null in the variable.

var myType = param as MyModel;
if (myType != null) { // you have what you need.
    ...
}

Another technique is the is operator (another good way). This works similar to as, but returns a Boolean rather than the object, or null, and you can inline it in an if statement to do the cast, and assign to a variable all in one line of code.

if (param is MyModel myType){
    // do something with myType
}

If you do add a base class to your models, you can use that type rather than the class name in the examples above. If you want, you can forego the base class and use a marker interface (an interface with no properties, or functions declared in it), and check for that type.

public interface IModel {}
public class MyModel : IModel {
    ...
}

if (param is IModel myType){
    // do something with myType
}

BTW, changing the folder name in the project didn't make any difference because C# works based on namespaces, and not folder structure, for most application types. As long as the folder and class files are included in the project, and the namespace is referenced, all is good.

Hope you find this information useful!

Upvotes: 2

Related Questions