Next, take notes from yesterday:
Add dynamic output for the first demo)
The key point of the entire application platform is to build dynamic output. In MVC, building data is the work of the controller, and rendering data as HTML is the work of the view, obviously, there is a process of passing data from the Controller to the view. One of the methods is through viewbag. viewbag is a member of the controller base class and is a dynamic object. We can assign any attribute value to it and present it in the view.
Modify the index action as follows:
public ViewResult Index()
{
int hour = DateTime.Now.Hour;
ViewBag.Greeting = hour < 12 ? "Good morning" : "Good afternoon";
return View();
}
We assigned the value of greeting to viewbag. If the system time is morning, the value of greeting is "good morning", and the value of "good afternoon" in the afternoon ", as mentioned above, viewbag will pass the data to the view. Modify the index view as follows:
@{
Layout = null;
}
<!DOCTYPE html>
<title>Index</title>
<body>
<div>
@ViewBag.Greeting,zhangxuefei(from the view)
</div>
</body>
Running the program will show our expected results (displayed in the morning: "Good morning, zhangxuefei (from the View)", displayed in the afternoon: "Good afternoon ....")
We experienced a viewbag. We only used V and C in the previous steps, but we didn't have any contact with M. Let's take a look at M (model)
Suppose: My friend decided to hold a New Year's Eve party. He hoped that we could create a website for him so that his friend could write down the participation information and necessary information.
It has the following functions:
1. display the home page of party Introduction 2. Registration Form 3. Form for necessary verification 4. Feedback to him after registration
Modify the view as follows:
<div>
@ViewBag.Greeting,zhangxuefei(from the view)
<p>We're going to have an exciting party.<br /></p>
@Html.ActionLink("RSVP Now", "RSVPForm")
</div>
Next we will create a very important part of the program m (model)
Model: represents the objects, processes, and rules of the real world. It defines the subject of the program and is known as the domain ). A model is called a domain model. It contains a C # object, also called a domain object, and all applications and methods that we can manipulate. View and controller expose the domain to the client in a persistent manner.
Add a model class named guestresponse, as shown below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace PartyInvites.Models
{
public class GuestResponse
{
[Required(ErrorMessage = "Please enter your name")]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter your email")]
[RegularExpression(".+\\@.+\\..+", ErrorMessage = "Please enter a valid email address")]
public string Email { get; set; }
[Required(ErrorMessage = "Please enter your phone number")]
public string Phone { get; set; }
[Required(ErrorMessage = "Please specify whether you'll attend")]
public bool? WillAttend { get; set; }
}
}
Here I have added the verification of the attribute value, which will be introduced later. The verification is also a very convenient place for Asp.net MVC. You may have noticed that willattend is defined as an empty type, and its values include true, false, and null. It is very necessary to define it as null, which is explained later.
We add a link in the homepage view: @ HTML. actionlink ("RSVP now", "rsvpform") jumps to the registration page. MVC provides us with many help classes for generating standard HTML elements. html is one of them.
The first parameter of the actionlink () method is the text displayed by the connection,
The second parameter is that the action for processing the URL request is rsvpform. You don't have to rush to know what help classes MVC provides for us. I am not in a hurry. I will introduce them later.
Add the following rsvpform action:
[HttpGet]
public ViewResult RsvpForm()
{
return View();
}
Then add a strongly typed view. Here, the strong type concept and the strong type dataset we usually call mean. The specific type we want to present here is guestresponse, you can directly create a strong type view, you must compile the program before right-clicking to add a view. Shows how to create a view:
Next, bind the form:
@ Model partyinvites. Models. guestresponse
@{
Layout = NULL;
}
<! Doctype HTML>
<HTML>
<Head>
<Title> rsvpform </title>
// Introduce a style sheet to control the display of verification information
<LINK rel = "stylesheet" href = "@ href ("~ /Content/site.css ")" type = "text/CSS"/>
</Head>
<Body>
@ Using (html. beginform ())
{
@ Html. validationsummary ()
<P>
Your name: @ html. textboxfor (x => X. Name) </P>
<P>
Your Email: @ html. textboxfor (x => X. Email) </P>
<P>
Your phone: @ html. textboxfor (x => X. Phone) </P>
<P>
Will you attend?
@ Html. dropdownlistfor (x => X. willattend, new [] {New selectlistitem () {text = "yes, I'll be there ",
Value = bool. truestring}, new selectlistitem () {text = "No, I can't come", value = bool. falsestring }}, "choose an option ")
</P>
<Input type = "Submit" value = "Submit RSVP"/>
}
</Body>
</Html>
Note the red part. When we create a strongly typed view, there will be one more sentence. It uses a Lambda expression, and lambda expressions all use an operator "=>". Read it as: goes to. If you are not familiar with me
"=>" You don't have to worry about becoming an obstacle to learning MVC. Click here to learn more "=> ".
There will also be a special introduction later, coming slowly, don't worry. Of course, you can also replace it with @ html. Textbox ("name") and @ html. Textbox ("email") without x => X. Name.
However, it is more convenient to use "=>" and it is not easy to write the wrong attribute name, because X => X. name has a smart prompt. This also involves an HTML. beginform () method, which will help us generate the form element and configure the method. By default, the current URL is submitted. The using statement is easy to misunderstand. here using and we are in ADO. the using is the same in net, and the using here is just equivalent to an end tag that we don't need to write </form>.
Note: For Asp.net webforms, A webform only supports a form with runat = "server" and contains the viewstate and PostBack logic. The form on the server is not used in MVC, all forms are common HTML tags, and the ID of the displayed HTML tag does not change.
Next, I want to start processing the created form. I just created an rsvpform action and added an attribute [httpget] to the action. this indicates that this action will only process get requests, and form forms are post requests by default. Therefore, create another action to process post requests, as shown below:
[Httppost]
Public viewresult rsvpform (guestresponse)
{
// Todo: email guestresponse to the part organizer
If (modelstate. isvalid) // jump to the thanks view only when the verification is passed
{
Return view ("thanks", guestresponse );
}
Else
{
// There is a validation error-redisplay the form
Return view ();
}
}
Reload the C # method that processes post and get requests into two methods to keep the code clean. Here, Action method is called by the same URL. MVC can ensure which method is called, once again, the idea that "conventions are better than configurations" is embodied. The above code imports a new namespace using partyinvites. models;
Model binding ):
As mentioned above, different requests (get/post) will have corresponding actions for processing. This is the MVC convention. When an action is called to respond to a URL request, how does guestresponse serve as a C # class before it?
What is the link? The answer is model binding.
Model binging: it is a very useful function in MVC. With the introduction of strong data conversion and key/value pairs, it is used to process attributes of the domain model type. The general process is as follows:
1. When the form data is created and sent to the client, the ID and name attributes corresponding to these values (these attributes inherit the attribute names of the surface classes in the model) are created.
2. Correspondingly, when model binding, the names attribute of the input element is used to set the attribute value of the model class instance and then transmitted to the action for processing.
We can see the following HTML code:
(The description above may not be clear. I can only say sorry, but now I can only understand it here, and I will share it later)
Model binding is a very powerful and customizable function. It eliminates the hard work of processing HTTP requests for us and enables us to focus more on processing C # objects instead of processing requests. form [] and request. the value of querystring. Return to the preceding rsvpform (). The guestresponse object is passed as a parameter to the action method. The action method (rsvpform () can automatically process the data from the form. The subsequent chapters will go deep into model binding, so if you don't understand it as well as me here, it doesn't matter, don't worry, and you will understand it later, huh, huh.
Next, create the thanks view (return view ("thanks", guestresponse), as shown below:
@ Model partyinvites. Models. guestresponse
@{
Layout = NULL;
}
<! Doctype HTML>
<HTML>
<Head>
<Title> thanks </title>
</Head>
<Body>
@{
Try
{
// It is mainly used to send emails. It is convenient. MVC provides webmail to help us send emails.
Webmail. smtpserver = "smtp.qq.com ";
Webmail. smtpport = 25;
Webmail. enablessl = false;
Webmail. Username = "mszhangxuefei ";
Webmail. Password = "private secrets ";
Webmail. From = "mszhangxuefei@foxmail.com ";
Webmail. Send (model. email, "RSVP notification", model. Name + (model. willattend ?? False )? "": "No") + "Participate ");
}
Catch (exception)
{
@: <B> sorry-we couldn't send the email to confirm your RSVP. </B>
}
}
<Div>
<H1>
Thank you, @ model. Name! </H1>
@ If (model. willattend = true)
{
@: It's greate That You're coming. The drinks are already in the fridge!
}
Else
{
@: Sorry to hear that you can't make it, but thanks for lew.us know.
}
</Div>
</Body>
</Html>
The @ operator provided by razor. Because view is strongly typed, I can get the value through @ model. attribute name.
Verification: when creating a model, some attributes are added to each attribute, which is very convenient for MVC.
In MVC, verification is a typical application in the domain model, rather than being verified on the user interface in webforms. This means that we can define verification rules only in one place. It takes effect in any other place that references the model. When adding attributes, we need to add a namespace: system. componentmodel. dataannotations.
Here we can explain why the willattend attribute is defined as an empty type, which is mainly used to verify null values. If the user does not select willattend, the verification will not pass. Of course, I used html. validationsummary () to display the authentication information in one place ().
At this point, we successfully completed the task assigned to us by our friends to invite people to join the New Year's Eve party. At this point, the notes of the first three chapters are explained here, and my study notes will be recorded continuously later.
I also just learned mvc3, and there will certainly be errors in my notes. Please give me more guidance. I would be very happy if I could help beginners like me a little.
Good night everyone!