MVC5 + EF6 + Bootstrap3 (12) new data, mvc5ef6

Source: Internet
Author: User

MVC5 + EF6 + Bootstrap3 (12) new data, mvc5ef6

Slark. NET-blog Park http://www.cnblogs.com/slark/p/mvc5-ef6-bs3-get-started-create.html

Series of tutorials: MVC5 + EF6 + Bootstrap3

Previous section: MVC5 + EF6 + Bootstrap3 (11) sorting, searching, and paging

Download source code: Click here to download

Directory
  • Preface
  • New Link
  • Create page Action
  • Create page View
  • Add data Action
  • View results
  • End
Preface

We have explained how to create a query page and add the sorting, search, and paging functions to the query page. Today, let's talk about how to add data to this list.

The order of explanation will be based on the time sequence of adding data, so that you can easily clarify the logical relationship. This section describes many knowledge points and new knowledge points. It helps you to learn new things and integrate them.

Preview The creation page as follows:

<H2> Students

The yellow part of the code above is the link to be added. The HTML code generated by this ActionLink is as follows:

<a href="/Company/Create">Add New Worker</a>

You can see that this link accesses the Create Action under CompanyController. Create the Action.

Create page Action

Open a file ~ \ Controllers \ CompanyController. cs. Add a Create Action to the Controller as follows:

public ViewResult Create(){       return View();}

So simple? In this case, all the information on the page for Data creation needs to be filled by the user. Naturally, no data is required to be transferred, so there is no operation.

This Action calls its corresponding View, so we will create this View.

Create page View

In ~ Create. cshtml view in the \ Views \ Company \ folder and write the following code:

 1 @model SlarkInc.Models.Worker 2 @{ 3     ViewBag.Title = "Add New Worker"; 4 } 5 

The 1st-line code of View is as follows, and the Worker class in the Models folder is introduced.

@model SlarkInc.Models.Worker

For better data operations, the Worker class has been modified. The changed code is as follows:

 1 using System.ComponentModel.DataAnnotations; 2 namespace SlarkInc.Models 3 { 4     public enum Sex 5     { 6         Male, Female 7     } 8     public class Worker 9     {     10         public int ID { get; set; }11         [Display(Name = "Last Name")]12         [DataType(DataType.Text)]13         [Required]14         public string LastName { get; set; }15         [Display(Name = "First Name")]16         [DataType(DataType.Text)]17         [Required]18         public string FirstName { get; set; }19         [Required]20         public Sex Sex { get; set; }21         public double? Rating { get; set; }22     }23 }

The DataAnnotations class library is introduced in line 1 of the Code, so that we can add metadata in the Worker class to better operate data in the View. For more information about this part, click here.

View the 13th line of code:

@Html.LabelFor(model => model.FirstName, new { @class = "control-label col-md-2" })

Here the LabelFor function is used to display the corresponding name of the data. It will find the data name corresponding to the FirstName of the Worker class, that is, the 15th row in the Model:

[Display(Name = "First Name")]

Then display it in Html as follows:

<label class="control-label col-md-2" for="FirstName">First Name</label>

Row 15th in View:

@Html.EditorFor(model => model.FirstName)

Based on the 16th rows in the Model:

[DataType(DataType.Text)]

To determine which input element to use to edit data. Since it is of the Text type, use the input of type = "text", as shown below:

<Input class = "text-box single-line" data-val = "true" data-val-required = "First Name field is required. "Id =" FirstName "name =" FirstName "type =" text "value =" "/>

In the above Code, the "data-val-required =" First Name field is required. "" Where did this paragraph come from?

This is the 17th rows that the EditorFor function reads to the Model:

[Required]

This line indicates that this data is required. If this line is left blank, the information "First Name field is required. ".

The Html. EnumDropDownListFor function is used in row 29th of the View, as shown below:

@Html.EnumDropDownListFor(model => model.Sex)

This function displays data of the Enum type in the following menu form on the page for editing.

However, this function is not so easy to use. First, the Visual Studio version must be 2013 or later, and the project must use MVC5, choose tool> library Package Manager> Manage NuGet packages for the solution from the menu. Select online as follows, search for MVC in the upper left corner, and install the latest version of MVC 5.2.2.

Public enum Sex {Male, Female}

The generated drop-down menu code is as follows:

<Select data-val = "true" data-val-required = "Sex field is required. "Id =" Sex "name =" Sex "> <option selected =" selected "value =" 0 "> Male </option> <option value =" 1 "> Female </option> </select>

View's 16th line code:

@Html.ValidationMessageFor(model => model.FirstName)

The ValidationMessageFor function is used to verify the data validity. It verifies whether the input value meets the requirements based on the type of this attribute in the Model. For example, if the Rating attribute is of the Double type, a prompt is displayed if the data is not a number and cannot be submitted.

Rows 6th, 7, and 46 of View are shown in the following Form function structure without parameters:

@using (Html.BeginForm()){}

If such a structure does not contain any parameters, Form will be submitted to the corresponding Controller and Action on this page using the Post method. Therefore, the HTML code generated by Form is as follows:

<form action="/Company/Create" method="post"></form>

In View, the structure of the Bootstrap horizontal form layout is as follows:

<div class="form-horizontal">    <div class="form-group">         <label class="control-label col-md-2" for=""></label>          <div class="col-md-10">          </div>    </div>    <div class="form-group">         <label class="control-label col-md-2" for=""></label>          <div class="col-md-10">          </div>    </div></div>

The result is as follows:

Each row corresponds to one attribute, the left is the attribute name, and the right is the edit box corresponding to the attribute. The col-md-2 for the property name represents 2/12 Of the total width of Form, and the col-md-10 represents 10/12 Of the total width of Form. This uses the Bootstrop raster system. For details about the raster system, click here.

View row 8th @ Html. AntiForgeryToken () function is used to defend against Cross-site request forgery (CSRF Cross-site request forgery ). This vulnerability can steal the identity of logon users and send malicious requests. For example, if a user logs on to an online bank and then accesses an attacker's website, the website will send a request to obtain bank information.

View line 11th uses Html. ValidationSummary (true ). Indicates that only Model-level verification error messages are output. The specific usage will be detailed in the following sections.

The above sections describe the representative technical knowledge points in the Create. cshtml file in detail. Other lines will not be repeated. If you have any questions, please leave a message.

Add data Action

From the code above, we can see that the Create. cshtml page will submit the data to the corresponding Controller and Action on the current page, so we will write the Action to process the submitted data under CompanyController. The Code is as follows:

 1 [HttpPost] 2 [ValidateAntiForgeryToken] 3 public ActionResult Create([Bind(Include = "FirstName, LastName, Sex, Rating")] Worker worker) 4 { 5     try 6     { 7         if (ModelState.IsValid) 8         { 9             db.Workers.Add(worker);10             db.SaveChanges();11             return RedirectToAction("Index");12         }13     }14     catch (DataException /* dex */)15     {16         ModelState.AddModelError("unableToSave","Unable to save changes.Try again, and if the problem persists see your system administrator.");17     }18     return View(worker);19 }

Note: We have previously written a Create Action to enter the add page. Here, Create is not to modify the previous Create. Instead, a new Action is created.

Row 1st adds [HttpPost] to the Action, indicating that the Action is called only when the Create Action is requested by the Post method.

Line 4 ValidateAntiForgeryToken is still the code written to prevent cross-site request forgery attacks.

The parameter of row 3rd Action is passed by the worker instance. That is to say, the four values submitted by Create. cshtml are assigned to work and then the worker is passed to Create as the parameter. [Bind (Include = "FirstName, LastName, Sex, Rating")] before this parameter is used to prevent overposting attacks. From the code of Create. cshtml, we can know that this page will only submit four values. Hackers can submit more values to the current Action through this page, and these extra values will also be added to the database in the worker instance, which is undoubtedly dangerous. Therefore, [Bind (Include = "")] limits that no matter how many values you submit, I only accept the four values "FirstName, LastName, Sex, Rating" in this Action. This ensures the security of the page.

Row 7th ModelState. IsValid indicates whether the submitted data is valid. For example, a number must be submitted for a numeric attribute to be valid. If the submitted data is valid, save the data and redirect the page back to Index. cshtml.

The ModelState. AddModelError () function of Row 3 can add an error message to the Model. The first parameter of the function is the key, which is used to find the error message. The second parameter is the specific content of the error message. You can use Html. ValidationMessage ("unableToSave") to access this error message in the View.

View results

Click the "Add New Worker" link.

If you leave the required item empty or enter invalid data, the following message is displayed:

Enter the correct information as follows:

Click the Submit button. The result is as follows:

End

I finally completed another article and made persistent efforts!

If you like it, we recommend it!

This section mainly references: Implementing Basic CRUD Functionality with the Entity Framework in ASP. net mvc Application

Previous section: MVC5 + EF6 + Bootstrap3 (11) sorting, searching, and paging

Author:Slark. NET

Source: http://www.cnblogs.com/slark/

The copyright of this article is shared by the author and the blog Park. You are welcome to repost this article. However, you must retain this statement without the author's consent and provide a clear link to the original article on the article page. Otherwise, you will be held legally liable. If you have any questions or suggestions, please give me some further information. Thank you very much.

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.