我是ASP.NET MVC的新手,我无法清楚地理解以下术语之间的区别:强类型视图、普通视图、部分视图和动态类型视图。请问有人能够为我描述一下吗?谢谢!
Strongly Typed view
一个视图将会绑定到这个视图模型。
public class MyViewModel
{
public string SomeProperty { get; set; }
}
public ActionResult Index()
{
var model = new MyViewModel();
model.SomeProperty = "some property value";
return View(model);
}
@model
指令,指向此视图模型:@model MyViewModel
...
<div>@Model.SomeProperty</div>
局部视图
视图和局部视图的区别在于,局部视图仅包含一些小的HTML片段,可以在普通视图的多个部分中重复使用。例如,您可以定义以下局部视图:
@model AddressViewModel
<div>Street: @Model.Street</div>
<div>Country: @Model.Country</div>
然后在你的主视图中多次呈现这个局部视图,以避免重复相同的代码:
@model MainViewModel
...
<h3>Personal address</h3>
<div>@Html.Partial("_Address.cshtml", Model.PersonalAddress)</div>
...
<h3>Business address</h3>
<div>@Html.Partial("_Address.cshtml", Model.BusinessAddress)</div>
动态类型视图
一种没有模型或使用弱类型结构(例如ViewBag
)的视图。例如,您可以有一个控制器操作,该操作在ViewBag
中设置某些属性:
public ActionResult Index()
{
ViewBag["SomeProperty"] = "some property value";
return View();
}
相应的视图中,您可以通过在ViewBag中使用相同的键来访问此属性:
<div>@ViewBag["SomeProperty"]</div>