我刚从书中得到一个例子
控制器:
[HttpPost]
public ViewResult RsvpForm(GuestResponse guestResponse)
{
// TODO: Email guestResponse to the part organizer
return View("Thanks", guestResponse);
}
看法:
@model MvcApplication1.Models.GuestResponse
@{
ViewBag.Title = "Thanks";
}
<div>
<h1>Thank you, @Model.Name!</h1>
@if (Model.WillAttend == true)
{
@:It's great that you're coming. The drinks are already in the fridge!
}
else
{
@:Sorry to hear that you can't make it, but thanks for letting us know.
}
</div>
我相信这种方法违背了分离视图和模型/控制器逻辑的概念。
我的做法是:
控制器:
[HttpPost]
public ViewResult RsvpForm(GuestResponse guestResponse)
{
ViewResult v = View("Thanks");
v.ViewBag.Name = guestResponse.Name;
if (guestResponse.WillAttend)
{
v.ViewBag.Message = "It's great that you're coming. The drinks are already in the fridge!";
}
else
{
v.ViewBag.Message = "Sorry to hear that you can't make it, but thanks for letting us know.";
}
return v;
}
看法:
@{
ViewBag.Title = "Thanks";
}
<div>
<h1>Thank you, @ViewBag.Name!</h1>
@ViewBag.Message;
</div>
这个“问题”的目的是澄清视图应该用于查看和控制器用于控制显示的内容,并且书籍示例是“不好的方法”(我正在考虑作者只是想展示能力的事实MVC)
现在使用强类型视图(带有逻辑代码)真的是个好主意,还是回到某种 ASP 意大利面条代码?
考虑到高质量的企业设计,请给出一些好的反馈
更新: 我知道这是一个简单的例子,没有这样的验证,但是将逻辑放在模型中,然后在视图上访问结果,这是否是一个好习惯(为了这个例子):
@Model.Message