The Web API service we will consume in this exercise is located at http://cartoonapi.azurewebsites.net/api/cartoon. It delivers the names of cartoon characters and their respective images.
1) To start with, create an ASP.NET Core Web application named TagHelperDemo in Visual Studio 2015.
2) We need to create a class that closely matches the nature of the Web API JSON object. Therefore, add the following CartoonCharacter class to a Models folder in your project:
public class CartoonCharacter {3) Next, we will need to install the We API Client libraries. To that end, execute the following commands from within the Package Manager Console window in Visual Studio 2015:
public string Name { get; set; }
public string PictureUrl { get; set; }
}
Install-Package Microsoft.AspNet.WebApi.ClientThis should add the following dependencies to your project.json file:
Install-Package System.Runtime.Serialization.Xml
"Microsoft.AspNet.WebApi.Client": "5.2.3",4) Add the following tag to the bottom of Views/Home/About.cshtml:
"System.Runtime.Serialization.Xml": "4.1.1"
<cartoon-characters></cartoon-characters>
5) Create a folder named TagHelpers and add to it a class file named CartoonCharactersTagHelper.cs. Have the class inherit from TagHelper and implement the ProcessAsync() method as follows:public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
}
We could have implemented a method Process() instead. However, in our case, it is appropriate to implement ProcessAsync() instead because we are about to make an async call to a remote service.
6) Add the following instance variable to the CartoonCharactersTagHelper class:
private string baseUrl = "http://cartoonapi.azurewebsites.net";
7) Annotate the CartoonCharactersTagHelper class with the following:
[HtmlTargetElement("cartoon-characters")]
[HtmlTargetElement(Attributes = "cartoon-characters")]
The first annotation defines the tag <cartoon-characters> and the second defines the “cartoon-characters” attribute. This means that we have two different ways to produce the same output on a razor .cshtml view.
8) Add the following method to the CartoonCharactersTagHelper class:
async Task<IEnumerable<CartoonCharacter>> GetCartoonCharactersAsync() {
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
IEnumerable<CartoonCharacter> cartoonCharacters = null;
try {
// Get all cartoon characters
HttpResponseMessage response = await client.GetAsync("/api/cartoon");
if (response.IsSuccessStatusCode) {
cartoonCharacters = response.Content.ReadAsAsync<IEnumerable<CartoonCharacter>>().Result;
}
} catch (Exception e) {
System.Diagnostics.Debug.WriteLine(e.ToString());
}
return cartoonCharacters;
}
The above code makes a request to the Web API service and returns an IEnumerable<CartoonCharacter> collection with the results.
9) Add the following code inside the ProcessAsync() method:
IEnumerable<CartoonCharacter> cartoonCharacters = await GetCartoonCharactersAsync();
string html = string.Empty;
html += "<table><tr><th>Name</th><th>Picture</th></tr>";
foreach (var item in cartoonCharacters) {
string photoUrl = baseUrl + "/" + item.PictureUrl;
html += "<tr>";
html += "<td>" + item.Name + "</td>";
html += "<td><img src='" + photoUrl + "' style='width: 50px' /></td>";
html += "</tr>";
}
html += "<tr><table>";
output.Content.SetHtmlContent(html);
The above code creates a table with the collection of cartoon characters so that it can be displayed wherever the tag helper is used.
11) Register the tag name in the Views/_ViewImports.cshtml file by adding the following to the list of tags that are already there:
@addTagHelper "TagHelperDemo.TagHelpers.CartoonCharactersTagHelper, TagHelperDemo"
You may need to adjust the above names depending on what you called your app and/or your tag helper class.
11) Compile and run your application then click on About. You should see the following output:
If you inspect the table in your browser, you will see the following:
The above is using the tag and not the attribute. Edit About.cshtml and comment out “<cartoon-characters></cartoon-characters>” and put the following <div> tag with the cartoon-characters attribute underneath it:
<div cartoon-characters></div>
Your About.cshtml should now look like this:@{When you run your application. you should see the same output as before. If you inspect the table you will see the following HTML source:
ViewData["Title"] = "About";
}
<h2>@ViewData["Title"].</h2>
<h3>@ViewData["Message"]</h3>
<p>Use this area to provide additional information.</p>
@*<cartoon-characters></cartoon-characters>*@
<div cartoon-characters></div>
This proves to us that you can either use tags or attributes with TagHelpers in ASP.NET Core.
No comments:
Post a Comment