ASP. 10 ways to expand your views

Source: Internet
Author: User
Tags html header actionlink

Original address: http://asp.net-hacker.rocks/2016/02/18/extending-razor-views.html
Jürgen Gutsch
Translation: Yang Xiaodong (savorboard)

Now, there are many ways to extend the razor view, and we'll start with the simplest one.
If you've been familiar with the views in MVC5 (and previous MVC), there's a part of you that you should already be familiar with. In the new ASP. NET core, some of the ways that you're familiar with are still available, but the Core version adds something to the view. Let's take a look at this article.

#1: Data View (Typed views)

This is a basic view that does not have dynamic content, that is, you define a viewmodel, and then ViewModel have some default values that are rendered directly on the view. Dead ViewModel, it seems, is not so common that you can't see it when you use Visual Studio to create a new default Web application. It looks like an *.cshtml ending HTML file, but the cshtml file is a file that the server can parse, so you can use some razor syntax, such as Htmlhelpers,urlhelpers. Similarly, you can use ViewBag or ViewData to transfer data from the Controller's action to the view to make it dynamic. But ViewBag and ViewData are weak type, so there is no smart hint, use up slightly uncomfortable.

To use a strongly typed data object in your view, you need to define a model to use in the view.

@model ExtendViews.ViewModels.AboutModel<!-- usage: --->@Model.FullName

Is this a very common approach? The next way is a better way to lay out our views:

#2: Layout (Layouts):

A master page that is equivalent to ASP. WebForms, but it is a way to define the basic layout of the Razor view. It is _Layout.cshtml located in the views\shared\ folder. Typically this file contains some of the HTML header,body and common things. You can build a few more combinations with each other to complete the layout of the entire site. When other pages refer to the Layout view page, they are written like this (note that the extension is not required):

@{    Layout = "_Layout";} 

This call needs to be in the first row of your view. But you don't need to define the layout in each view, and if you create a new ASP. NET core project using Visual Studio, the Views folder has one _ViewStart.cshtml , which is automatically imported into each view when it is run.

In _Layout.cshtml a method called RenderBody() , it is used to render detailed view pages into the template layout view:

@RenderBody()

The details view will be rendered here at the location of this method.

#3: Area (Sections)

Sometimes in a sub-view you want to display some HTML code, such as JavaScript code or CSS, in the main master, you can use sections at this point, usually at the end of the page.

Define a javascripts section in the main view ( _Layout.cshtml ):

@RenderSection("scripts", required: false)

There is a required parameter to declare whether this section is required. You can then use this in a child view:

@section scripts{    <script>        $(function() { // some more js code here; }); </script>}

If you use nested layouts, you might want to nest this area. It means that you nest calls within a section RenderSection() :

@section scripts{    @RenderSection("scripts", required: false)}
#4: Partial view (partialviews)

You can extract the reusable part of the HTML page and put it in a new Razor view, which has no action, and this view is called a partial view. A partial view is usually also in a Views\Shard\ folder.

The partial view can also be a data view, which can fetch data from the parent view (but not required):

@model IEnumerable<UserModel>@if (Model.Any()){    <ul>        @foreach (var user in Model)        {            <li>@user.FullName</li> } </ul>}

This partial view needs to get the data of the user list from the parent view

@{ await Html.RenderPartialAsync("Users", Model.Users);}

If your partial view does not define a user model, you do not need to pass the second parameter.

#5: View Components (viewcomponents)

Unique to this ASP.

Translator Note: Similar to the previous user control

Sometimes you need to do some partial view, but it also contains some business logic inside. In the past, you can use Childaction to render results to a view, but in ASP. NET core there is a new way to do this, and it is ViewComponents (I have written a blog post about viewcomponents). It is similar to a mini-MVC in MVC, which means that they can have their own controller, and a single action and view. ViewComponentsis completely independent of your current view, but you can transfer data through your current view.

To invoke it like this, to render a ViewComponents :

@Component.Invoke("Top10Articles");

You can read my blog to learn how to create your own ViewComponent .

#6: HTML Helper (htmlhelpers)

In the HTMLHelper class, you can create your own extension method to extend the razor syntax:

public static class HtmlHelperExtensions{    public static HtmlString MyOwnHtmlHelper(this HtmlHelper helper, string message) { return new HtmlString($"<span>{message}<span>"); }}

In your view, it is useful to create a reusable part that contains more business logic than a partial view. The new taghelpers is better than the htmlhelpers extension, but when you expand your view, Htmlhelpers still has some of its own places to apply.

#7: Label Helper (taghelper)

This is a very good new feature of ASP.

A small helper that expands your view, it looks like a native HTML tag. In ASP. You should use Taghelpers to replace htmlhelpers because they are more concise and easy to use. Another great benefit is the dependency injection, which is not used in htmlhelpers because the htmlhelpers extends to static content. But Taghelpers is a public class, and we can easily inject services into its constructors.

Here's a very simple little example to show how to define a taghelper:

 [targetelement ( "HI")] public Span class= "Hljs-keyword" >class hellotaghelper: TagHelper {public override void process (TagHelperContext Context, Taghelperoutput output) {output. TagName =  "P"; output. Attributes.Add ( "id", context. UNIQUEID); Output. Precontent.setcontent ( "Hello"); Output. Postcontent.setcontent (string. Format ( "hh:mm"));}}  

This defines a label called hi , which is rendered as an HTML tag, and the content of the P tag is the current time.

Use:

<hi>John Smith</hi>

Results:

<p>Hello John Smith, time is now: 18:55</p>

ASP. NET Core MVC already provides many taghelpers by default to replace the previous htmlhelpers. For example ActionLink has been replaced by the new taghelper:

@Html.ActionLink(“About me”, “About”, “Home”)

The new taghelper like this to create a link:

<a asp-controller=”Home” asp-action=”About”>About me</a>

The above two ways to create a result of a label:

<a href=”/Home/About”>About me</a>

As you can see, taghelpers looks more like native HTML, they are more intuitive in view, more readable, and easier to use.

#8: Dependency Injection (Dependency injection)

This is also a new feature of ASP.

You can use dependency injection when extending your view, which is a very big improvement. Yes, you can use di in your view.

In StackOverflow and Reddit, did someone ask?
Does it really make sense? Isn't that going to mess up my view? Is this not a deviation from the MVC pattern?

I think that is not the case. Indeed, you use it where you really need it, and you need to be very careful when you use it. There is such a valid scenario: You create a form to edit the user profile information, the user can add his company location, address, National city, etc., I do not want to transfer the company location, address and country city from action to view. I'm only willing to use the user profile, which I want to process the user profile in Action. This can be injected into the service to query the data for me, which is why it is very useful in this case. It can keep our action and viewmodel very clean.

In Startup.cs the ConfigureServices to register your specific service, then you can use it in the view, just one line of code:

@inject DiViews.Services.ICountryService CountryService;

Now you can use it in your view ContryService to populate the country drop-down list.

I wrote a lot about dependency injection in this blog post.

#9: function (Functions)

In an ASP. NET MVC project, I never really used this function. I used it only once in a Umbraco CMS system. In any case, this is another tip to extend your view. Perhaps you have a very complex view of business logic, in which case you can write C # methods in your view:

@functions{    public string ReverseString(string input) { return String.Join("", input.Reverse()); }}
#10: Configuring the Global View Configuration

Finally, you can _ViewImports.cshtml configure some of the more common using references, dependency injection, etc. used in your other views in the file.

Summarize

Both the previous MVC and the new core MVC have many ways to extend the view, although the way to extend these views is somewhat similar, but each has its best fit, so when we use these features to solve our problems, we should think more and find the most appropriate way.

Translator Note: This translation is not verbatim translation, due to the level of limited, inevitably there are some errors and inaccurate translation of the place, I hope readers can point out and will be very grateful.

ASP. 10 ways to expand your views

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.