I m wondering a MVC model class may have functions in them or not ? I want to use these methods in View to accept an argument and do some business logic.
Is it standard or a bad idea ? Or is any issue associated with this approach ?
I m wondering a MVC model class may have functions in them or not ? I want to use these methods in View to accept an argument and do some business logic.
Is it standard or a bad idea ? Or is any issue associated with this approach ?
In my eyes no, its not standard unless if in your mind Models are not just simple classes...
Try this:
Keep your models separated:
-Models that serve your business layer and your data access layer. Lets call them just Models
.
-Models that serve your MVC views. Lets call them ViewModels
.
Then try to see your controllers as traffic police officers. Let them just take the request and assign someone to do the actual job.
This means that its better to create 2 separate parts in your application.
-The business Layer. -The Data access Layer.
If the app is small you could make the 2 above layers one.
So after all that you will have:
-Controllers talk to Views with ViewModels. -Controllers talk to Business / Data access layer using Models.
So keep your models
and viewmodels
thin and do the business logic NOT in the controller but in separate layers (it could be another project or just another class in your project).
Additional Info:
You could have your models like:
public class Course
{
public int CourseId { get; set; }
public string CourseName { get; set; }
}
public class Faculty
{
public int FacultyId { get; set; }
public string FacultyName { get; set; }
public List<Course> AllotedCourses { get; set; }
}
public class Student
{
public int EnrollmentNo { get; set; }
public string StudentName { get; set; }
public List<Course> EnrolledCourses { get; set; }
}
Your ViewModel:
public class ViewModelDemoVM
{
public List <Course> allCourses { get; set; }
public List <Student> allStudents { get; set; }
public List <Faculty> allFaculties { get; set; }
}
Then create a separate class that will handle the models and return viewmodels for controllers to pass to views and vice versa.
I usually put all business logic inside the model classes and try to make the controllers as stupid as possible.
Personally, I think you shouldn't put any business logic in view unless there's no other way around.
May be you could show us your code and it's easier to discuss from there.