Pro ASP. NET Core MVC 6th Chapter 2 (Chapter Two), coremvc

Source: Internet
Author: User

Pro ASP. NET Core MVC 6th Chapter 2 (Chapter Two), coremvc
Add dynamic output

The focus of the entire web application platform is to build and Display Dynamic Output content. In MVC, the Controller is responsible for building some data and passing it to the view. The view is responsible for rendering it into HTML. One way to transmit data from a controller to a view is to use the ViewBag object, which is a member of the controller base class. ViewBag is a dynamic object. You can assign any attribute to it for rendering. Code 2-5 demonstrates how to pass simple objects in HomeController. Listing 2-5. Set View data

using System;
using Microsoft.AspNetCore.Mvc;
namespace PartyInvites.Controllers {
public class HomeController : Controller {
public ViewResult Index() {
int hour = DateTime.Now.Hour;
ViewBag.Greeting = hour < 12 ? "Good Morning" : "Good Afternoon";
return View("MyView");
}
}
}
I assign a value to the viewbag.greeting property to provide data to the view. The greeting property does not exist before the assignment, which allows me to pass data from the controller to the view in any fluent way without having to define the class before the assignment. I referenced the viewbag.greeting property in the view to get its value. As in code 2-6, this is the modified myview.cshtml.
Listing 2-6. Get the passed value in the view
[H]
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@ViewBag.Greeting World (from the view)
</div>
</body>
</html>
The added part of the above code is the razor expression, which is evaluated when MVC generates the corresponding view. When I call the view method in the controller, MVC finds the myview.cshtml file and requests the razor view engine to parse the contents of the file. Razor looks for expressions like those in the code above. In this case, the processing expression means inserting the viewbag.greeting property into the view.
There's nothing special about greeting. You can use any other name, and it's just as easy to use. As long as your name in the controller is the same as that in the view. You can use multiple properties to pass multiple data. Then you run it to see the effect, 2-13.
Figure 2-13 dynamic response of an MVC to create a simple data entry application
In the rest of this chapter, I will explore more basic MVC features by building a simple data entry application. In this section, I will speed up. My goal is to demonstrate MVC with action, so I'll go over some of the internal principles of some things. But don't worry, I'll talk about that in a later chapter. Setting scene
Imagine a friend who decided to hold a new year's party and asked me to build a web app to track the friends it invited through an e-invitation. She needs four key functions:
A home page for information about the party.
A form to fill in invitations.
The invitation needs to be verified and a thank you page is displayed.
A summary page to show who will attend the party.
In the following paragraphs, I will gradually add content and functions based on the previous MVC project. First, I will implement the first item in the list immediately, because I have done some work before, just add some HTML to the existing view to give the information of the party. Code 2-7 shows what I added to the views / home / myview.cshtml file.
Listing 2-7. Show party details
[H]
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@ViewBag.Greeting World (from the view)
<p>We're going to have an exciting party.<br />
(To do: sell it better. Add pictures or something.)
</p>
</div>
</body>
</html>
I go on. If you run, you'll see the party information, (well, some placeholders, but you've got it) 2-14
Figure 2-14 add HTML to the view and add a data model
In MVC, M represents the model, which is the most important part of the application. Model is the representation, processing and definition of real world objects. Models are often called domain models, which contain C ා objects (domain objects) that make up the world of applications and the methods to manipulate them. Views and controllers expose domains to clients in a consistent manner, and a well-designed MVC application should start with a well-designed model. The controller and view are then added.
In the PartyInvites project, I don 't need a complex model, because this is a very simple application. I just need to establish a domain class, and then I will call GuestResponse. this object will be responsible for saving, verifying and confirming an invitation.
MVC generally places models in the models folder. To create this folder, right-click the partyinvites project, select Add - > new folder from the menu, and then set the name to models.
Note: you cannot set the name of a folder when the program is running. You can select Stop debugging from the debug menu, right-click the new folder item you have added, and then select Rename from the pop-up menu, and change it to models.
To create a class file, right-click the models folder and choose add - > class from the pop-up menu. Set the new class name to guestresponse.cs, and then click the Add button to edit the content of the new class as code 2-8
Listing 2-8 guestresponse domain class definition
namespace PartyInvites.Models {
public class GuestResponse {
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public bool? WillAttend { get; set; }
}
}
Tip: you may have noticed that the willappend property is a nullable bool type, meaning it can be true, false, or null. I'll explain her rationale in the "add verification" section of this chapter. Create a second action and strongly typed view
One goal of my application is to include an invitation form for which I'm going to define an action method to receive requests. A single controller class can define multiple action methods. The default convention is to place related actions in the same controller. Code 2-9 shows the new action method added to the home controller.
Listing 2-9. Adding an Action Method in the HomeController.cs File
using System;
using Microsoft.AspNetCore.Mvc;
namespace PartyInvites.Controllers {
public class HomeController : Controller {
public ViewResult Index() {
int hour = DateTime.Now.Hour;
ViewBag.Greeting = hour < 12 ? "Good Morning" : "Good Afternoon";
return View("MyView");
}
public ViewResult RsvpForm() {
return View();
}
}
}
The rsvpform action method calls the view method without parameters. This will tell MVC to take the default view connected to the action method by rendering, which is the same as the name of the action method. Here is rsvpform.cshtml. Right click the views - > home folder and select Add - > new item from the pop-up menu. Select MVC view page template from asp.net category, set the new name as rsvpform.cshtml, and click Add to create the file. Modify the contents of the file to make it code 2-10.
Listing 2-10. Setting view file
@model PartyInvites.Models.GuestResponse
[H]
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>RsvpForm</title>
</head>
<body>
<div>
This is the RsvpForm.cshtml View
</div>
</body>
</html>
Most of the above content is HTML, with @ model razor expression in the middle to create a strongly typed view. A strongly typed view is used to render a specific type of model. If I specify a type (in this case, the guestresponse class), MVC can create some useful shortcuts and make it easier. I'll take advantage of strong type features later. To test the new action method and its view, start the application and browse / home / rsvpform using a browser. MVC will use the naming convention to redirect requests to the rsvpform action method in the home controller. This action method tells MVC to render the default view. Here, another naming convention is used to render rsvpform.cshtml. Figure 2-15 shows the results.
Figure 2-15 rendering the second view connection action method
I want to establish a connection from within my view so that my guests can see the rsvpform view without having to know the URL. As code 2-11.
Listing 2-11. Add a connection to myview.cshtml
[H]
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@ViewBag.Greeting World (from the view)
<p>We're going to have an exciting party.<br />
(To do: sell it better. Add pictures or something.)
</p>
<a asp-action="RsvpForm">RSVP Now</a>
</div>
</body>
</html>
The added part of the code is a < a > tag with the ASP action attribute. This is a tag helper attribute, which is an instruction for Razor to execute when the view is rendered. The ASP action attribute here is used to add an href attribute to the < a > tag, including the URL to an action method. I'll end chapters 24, 25, and 26 with the appropriate tag helper. But here is a simple tag helper for < a > tags, which tells razor to insert the URL of an action method defined in the same controller as this view. You will see this link when the program is running. 2-16.
Figure 2-16 add links between action methods
Start the application and place the mouse over the RSVP now connection. You will see that the connection points to the following URL (the port may be different): http: / / localhost: 57628 / home / rsvpform
An important principle here is that you should use MVC to generate URLs instead of hard coding in your view. When the tag helper establishes the href attribute for the < a tag, it checks the configuration of the current application and calculates what the URL looks like. This allows you to change the application configuration to support different URL formats without having to update the view. I will explain the principle in Chapter 15. Create forms
Now that I have established a strongly typed view and can connect to it in the index view, I will add some content to the rsvpform.cshtml file and make them an HTML form to edit the guestresponse object, such as code 2-12.
Listing 2-12. Create an input form view
@model PartyInvites.Models.GuestResponse
[H]
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>RsvpForm</title>
</head>
<body>
<form asp-action="RsvpForm" method="post">
<p>
<label asp-for="Name">Your name:</label>
<input asp-for="Name" />
</p>
<p>
<label asp-for="Email">Your email:</label>
<input asp-for="Email" />
</p>
<p>
<label asp-for="Phone">Your phone:</label>
<input asp-for="Phone" /></p>
<p>
<label>Will you attend?</label>
<select asp-for="WillAttend">
<option value="">Choose an option</option>
<option value="true">Yes, I'll be there</option>
<option value="false">No, I can't come</option>
</select>
</p>
<button type="submit">Submit RSVP</button>
</form>
</body>
</html>
I have defined a label and input element for each attribute of the guestresponse model class. Each element uses the ASP for attribute to connect the attributes of a model. Here, ASP for is another tag helper that can be configured to connect elements to model objects. Here is an example of HTML generated by tag helper and sent to browser:
<p>
<label for="Name">Your name:</label>
<input type="text" id="Name" name="Name" value="">
</p>
Here, the ASP for helper on the label can set a value for the for property. ASP for on the input element can set the ID and name of the element. None of this is for a particular purpose, but you'll see that connecting elements to attributes of the model can bring more benefits. You will see that more ASP action attributes are applied to the form element. It uses the URL routing configuration of the application to set the action attribute of the form to a URL that points to a special action method, as follows:
The < form method = "post" action = "/ home / rsvpform" > is the same as the assistant attribute I applied to the element. The advantage of this method is to change the URL system used by the application, and the content generated by the label assistant will reflect the automatic change. Run the application and click RSVP now to see the window, 2-17.
Figure 2-17 adding links between action methods to receive data
I haven't told MVC what I want to do when the form is sent to the server. For now, clicking the submit RSVP button simply clears the values you enter into the form. That's because the form sends the data back to the rsvpform action method of the home controller and only tells MVC to render the view again. Nothing else is done. To receive and process submitted form data, I will use the core controller functionality. I will add a second rsvpform action method to create the following:
A way to respond to HTTP get requests: every time a browser clicks a link, it usually raises a get request. This version of the action method will display a blank form the first time a user accesses home / rsvpform.
A way to respond to HTTP post requests: by default, forms using HTML. Beginform() are submitted by browsers using post requests. This version of the action will be responsible for accepting the submitted data and deciding what to do with it next. Using different C methods to process get and post requests will make your code look more concise. Because the two methods should perform different duties. Both methods will be raised by the same URL, but MVC can make sure to call the appropriate method according to the get request or post request. Code 2-13 shows the changes made by the homecontroller class.
Listing 2-13. Add an action method to support post request
using System;
using Microsoft.AspNetCore.Mvc;
using PartyInvites.Models;
namespace PartyInvites.Controllers {
public class HomeController : Controller {
public ViewResult Index() {
int hour = DateTime.Now.Hour;
ViewBag.Greeting = hour < 12 ? "Good Morning" : "Good Afternoon";
return View("MyView");
}
[HttpGet]
public ViewResult RsvpForm() {
return View();
}
[HttpPost]
public ViewResult RsvpForm(GuestResponse guestResponse) {
// TODO: store repsonse from guest
return View();
}
}
}
I have added an httpget attribute to the existing rsvpform action method, which tells MVC that this method can only be called by get request. Then I added an overloaded version of the rsvpform method that accepts the guestresponse object. I applied the httppost feature to this method. It tells MVC that the new method will handle post requests. I'll show you how the code works in later paragraphs. I also introduced a namespace called partyinvites. Models. It was added to allow me to use the guestresponse model type. Use model binding
The first overloaded rsvpform action method renders the same view as before -- rsvpform. Cshtml -- to generate a form like figure 2-17. The second overload is more interesting, but considering that the action method will be called in response to the HTTP post request, the guestresponse type is a C ා, how are the two connected?
The answer is model binding, a useful MVC function in which the input data is parsed into key / value pairs in HTTP requests, which are used to fill in properties of domain model types. Model binding is a powerful and customizable function, which can eliminate running in and directly process HTTP requests, and let you use C ා objects instead of processing a single data value sent by the browser. The guestresponse object passed as a parameter to the action method automatically populates the data in the form field. In Chapter 26, I will introduce

Related Article

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.