[英]How MVC separate business logic from UI in ASP.NET MVC?
I'm a beginner in ASP.NET MVC and Design Pattern.我是 ASP.NET MVC 和设计模式的初学者。 still struggling to understand how MVC separate business logic from UI/View.仍在努力理解 MVC 如何将业务逻辑与 UI/View 分开。
Let's say we have this scenario:假设我们有这样的场景:
There is an Employee model with a property of TotalSales for the total sales of this month, and there is also an default Index view.有一个 Employee 模型,其属性为 TotalSales,用于表示本月的总销售额,还有一个默认的 Index 视图。
so in the view, razor engine should populate employee's details such as name, gender, department etc. So we just need to pass a view model to the view, which seems to be working well.所以在视图中,剃刀引擎应该填充员工的详细信息,如姓名、性别、部门等。所以我们只需要向视图传递一个视图模型,这似乎工作得很好。 But let's say I want to the UI/HTML also display an extra paragraph "This employee is a good employee" if the employee's TotalSales > 10000 this month, otherwise display "This employee needs to improve his marketing skill".但是,假设我希望 UI/HTML 还显示一个额外的段落“该员工是一个好员工”,如果该员工本月的 TotalSales > 10000,否则显示“该员工需要提高他的营销技巧”。 So in the view template, I have to code like this:所以在视图模板中,我必须这样编码:
@if (employeeInstance.TotalSales > 10000)
{
<p>This employee is a good employee</p>
}else
{
<p>This employee needs to improve his marketing skill</p>
}
but isn't the the business logic is mixed inside the view, which is against the goal of MVC pattern?但是业务逻辑不是混在视图里面,违背了MVC模式的目标吗?
you can use your logic in model.您可以在模型中使用您的逻辑。 like if you have model like below就像你有像下面这样的模型
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public double TotalSales { get; set; }
public string Comment
{
get
{
if (TotalSales > 10000)
{
return "This employee is a good employee";
}
else
{
return "This employee needs to improve his marketing skill";
}
}
}
}
now you can use Comment
property in your view现在您可以在视图中使用Comment
属性
<p>@Model.Comment</p>
also you can set this employee in your business layer and bind this to your view model and use in your view so using this you can separate your business logic from your view and not required to set your logic in controller.您也可以在您的业务层中设置此员工并将其绑定到您的视图模型并在您的视图中使用,因此使用它您可以将您的业务逻辑与您的视图分开,而不需要在控制器中设置您的逻辑。 let me know if require more information :).如果需要更多信息,请告诉我:)。
Do logic in Controller by return ViewBag (or you return ViewModel)通过返回 ViewBag(或者您返回 ViewModel)在控制器中执行逻辑
Controller控制器
if (employeeInstance.TotalSales > 10000){
ViewBag.employeetext = "This employee is a good employee";
}
else{
ViewBag.employeetext = "This employee needs to improve his marketing skill";
}
View看法
<p>@ViewBag.employeetext</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.