Strongly Typed view vs Normal View vs Partial View

2019-03-27 16:45发布

问题:

I am Newer in ASP.NET MVC. I can not Clearly Understand the difference among

Strongly Typed view vs Normal View vs Partial View vs Dynamic-type View

in Asp.NET MVC. Anyone describe me about this terms.

Thanks in advance!!!

回答1:

Strongly Typed view

A view which is bound to a view model. For example if you have the following view model:

public class MyViewModel
{
    public string SomeProperty { get; set; }
}

that is passed to the view by the controller action:

public ActionResult Index()
{
    var model = new MyViewModel();
    model.SomeProperty = "some property value";
    return View(model);
}

the strongly typed view will have the @model directive at the top pointing to this view model:

@model MyViewModel
...
<div>@Model.SomeProperty</div>

Partial View

The difference between a view and a partial view is that a partial view only contains some small HTML fragments that can be reused in multiple parts of a normal view. For example you could define the following partial view:

@model AddressViewModel
<div>Street: @Model.Street</div>
<div>Country: @Model.Country</div>

and then render this partial view at multiple places in your main view to avoid repetition of the same code over and over:

@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>

Dynamic-type View

A view which doesn't have a model or one that uses weakly typed structures such as ViewBag. For example you could have a controller action which sets some property in the ViewBag:

public ActionResult Index()
{
    ViewBag["SomeProperty"] = "some property value";
    return View();
}

and the corresponding view you could access this property by using the same key in the ViewBag:

<div>@ViewBag["SomeProperty"]</div>