MVC 模型类中的函数?

use*_*510 1 .net c# asp.net-mvc asp.net-mvc-4

我想知道 MVC 模型类中是否有函数?我想在 View 中使用这些方法来接受一个参数并做一些业务逻辑。

这是标准还是坏主意?或者是否有与此方法相关的任何问题?

e4r*_*dog 5

在我看来不,它不是标准的,除非在你看来模型不仅仅是简单的类......

尝试这个:

保持模型分开:

- 为您的业务层和数据访问层提供服务的模型。让我们称他们为Models

- 为您的 MVC 视图提供服务的模型。让我们打电话给他们ViewModels

然后尝试将您的控制器视为交通警察。让他们接受请求并指派某人来完成实际工作。

这意味着最好在您的应用程序中创建 2 个单独的部分。

- 业务层。- 数据访问层。

如果应用程序很小,您可以将上面的 2 层设为一层。

所以毕竟你将拥有:

-Controllers 用 ViewModels 与 Views 对话。- 控制器使用模型与业务/数据访问层对话。

因此,保持你modelsviewmodels薄,并在控制器不做的业务逻辑,但在不同的层(它可以在你的项目中的另一个项目或只是另一个类)。

附加信息:

你可以让你的模型像:

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; }
}
Run Code Online (Sandbox Code Playgroud)

你的视图模型:

public class ViewModelDemoVM
{        
    public List <Course> allCourses { get; set; }
    public List <Student> allStudents { get; set; }
    public List <Faculty> allFaculties { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后创建一个单独的类来处理模型并返回控制器的视图模型以传递给视图,反之亦然。