Implement basic addition, deletion, query, modification, and deletion Functions

Source: Internet
Author: User
Tags actionlink

Implement basic addition, deletion, query, modification, and deletion Functions

1.

In the previous tutorial you created an MVC application that stores and displays data using the Entity Framework and SQL Server LocalDB. in this tutorial you'll review and customize the CRUD (create, read, update, delete) code that the MVC scaffolding automatically creates for you in controllers and views. in the previous course, you used Entiey Framework and SQL Server LocalDB to create an MVC application that can store and display data. In this lesson, you will review and customize the MVC Framework to add, query, modify, and delete functions automatically created for your controllers and views.

2.NoteIt's a common practice to implement the repository pattern in order to create an Authorization Action layer between your controller and the data access layer. to keep these tutorials simple and focused on teaching how to use the Entity Framework itself, they don't use repositories. for information about how to implement repositories, see the ASP. NET Data Access Content Map.

Note: We usually implement the warehousing mode, which can be achieved by creating an abstraction layer between your controller and the data access layer. To keep this course simple and focus on how to use EF itself, we do not use the warehouse mode. For more examples of how to implement the warehouse mode, please refer to the link article.

In this tutorial, you'll create the following web pages:

In this course, you will create the following Web page:

3. Create a Details Page -- Create a detailed list Page
The scaffolded code for the Students Index page left out the Enrollments property, because that property holds a collection. in the Details page you'll display the contents of the collection in an HTML table. this MVC Framework Code reserves the Enrollments attribute for the student list page, because this attribute is a set. On the detail list page, you will form an HTML table, to display the content of the set. In Controllers \ StudentController. cs, the action method for the Details view uses the Find method to retrieve a single Student entity.
   // GET: Students/Details/5        public ActionResult Details(int? id)        {            if (id == null)            {                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);            }            Student student = db.Students.Find(id);            if (student == null)            {                return HttpNotFound();            }            return View(student);        }
Route dataRoute data is data that the model binder found in a URL segment specified in the routing table. For example, the default route specifies controller, action, and id segments: routes.MapRoute(    name: "Default",    url: "{controller}/{action}/{id}",    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });In the following URL, the default route maps Instructor as the controller, Index as the action and 1 as the id; these are route data values.http://localhost:1230/Instructor/Index/1?courseID=2021"?courseID=2021" is a query string value. The model binder will also work if you pass the id as a query string value:http://localhost:1230/Instructor/Index?id=1&CourseID=2021The URLs are created by ActionLink statements in the Razor view. In the following code, the id parameter matches the default route, so id is added to the route data. @Html.ActionLink("Select", "Index", new { id = item.PersonID  })In the following code, courseID doesn't match a parameter in the default route, so it's added as a query string.@Html.ActionLink("Select", "Index", new { courseID = item.CourseID }) 

4.

Open Views \ Student \ Details. cshtml. each field is displayed using a DisplayFor helper, as shown in the following example: Open the Details page, Each field uses the DisplayFor auxiliary method: the yellow part is the modified <dl class = "dl-horizontal"> <dt> @ Html. displayNameFor (model => model. lastName) </dt> <dd> @ Html. displayFor (model => model. lastName) </dd> <dt> @ Html. displayNameFor (model => model. firstMidName) </dt> <dd> @ Html. displayFor (model => model. firstMidName) </dd> <dt> @ Html. displayNameFor (model => model. enrollmentDate) </dt> <dd> @ Html. displayFor (model => model. enrollmentDate) </dd> <dt> @ Html. displayNameFor (model => model. enrollments) </dt> <dd> <table> <tr> <th> Course Title </th> <th> Grade </th> </tr> @ foreach (var item in model. enrollments) {<td> @ Html. displayFor (s => item. course. title) </td> <td> @ Html. displayFor (s => item. grade) </td >}</table> </dd> </dl>

This code loops through the entities inEnrollmentsNavigation property. For eachEnrollmentEntity in the property, it displays the course title and the grade. The course title is retrieved fromCourseEntity that's stored inCourseNavigation property ofEnrollmentsEntity. All of this data is retrieved from the database automatically when it's needed. (In other words, you are using lazy loading here. You did not specifyEager loadingForCoursesNavigation property, so the enrollments were not retrieved in the same query that got the students. Instead, the first time you try to accessEnrollmentsNavigation property, a new query is sent to the database to retrieve the data. You can read more about lazy loading and eager loading in the Reading Related Data tutorial later in this series .)

This loop Code uses the Enrollments navigation attribute. Each Enrollment object displays the course title and score in this attribute. The course title is obtained from the course baohang attributes stored in the enrollments entity. All the data is automatically read from the database as needed. (For more information about lazy loading, see the link)

Run the page by selectingStudentsTab and clickingDetailsLink for Alexander Carson. (If you press CTRL + F5 while the Details. cshtml file is open, you'll get an HTTP 400 error because Visual Studio tries to run the Details page but it wasn't reached from a link that specifies the student to display. in that case, just remove "Student/Details" from the URL and try again, or close the browser, right-click the project, and clickView, And then clickView in Browser.)

 

Update the Create Page -- Update the new Page

InControllers \ StudentController. cs, ReplaceHttpPost CreateAction method with the following code to addtry-catchBlock and removeIDFrom the Bind attribute for the scaffolded method:

In the Student controller, replace the Create method with the following code, add an exception handling statement for the Create method, and then remove the ID binding attribute.

// POST: Students/Create // to prevent "too many releases" attacks, Please enable specific properties to bind, for // details, see http://go.microsoft.com/fwlink? LinkId = 317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create ([Bind (Include = "LastName, FirstMidName, EnrollmentDate")] Student student) {try {if (ModelState. isValid) {db. students. add (student); db. saveChanges (); return RedirectToAction ("Index") ;}} catch (DataException/* dex */) {// Log the error (uncomment dex variable name and add a line here to write a log. modelState. addModelError ("", "Unable to save changes. try again, and if the problem persists see your system administrator. ");} return View (student );}

This code addsStudentEntity created by the ASP. net mvc model binder toStudentsEntity set and then saves the changes to the database .(Model binderRefers to the ASP. net mvc functionality that makes it easier for you to work with data submitted by a form; a model binder converts posted form values to CLR types and passes them to the action method in parameters. in this case, the model binder instantiatesStudentEntity for you using property values fromFormCollection .)

This Code adds the Student Entity Created by binding the ASP. net mvc model. Model binding, corresponding to the Student object, and saved to the database. (Model binding refers to ASP. net mvc is a function that enables you to better submit data through a form. Model binding converts the form value to the CLR type and then passes it to the Action method as a parameter. In this case, the model is bound to a Student object through the attribute value in the form set)

You removedIDFrom the Bind attribute becauseIDIs the primary key value which SQL Server will set automatically when the row is inserted. Input from the user does not setIDValue.

You removed the low-end ID from the model binding. Because ID is the primary key, it is automatically executed when the SQL insert operation is executed, no ID value is entered.

 

Security Note:TheValidateAntiForgeryTokenAttribute helps prevent cross-site request forgery attacks. It requires a correspondingHtml.AntiForgeryToken()Statement in the view, which you'll see later.

TheBindAttribute is one way to protect againstOver-postingIn create scenarios. For example, supposeStudentEntity includesSecretProperty that you don't want this web page to set.

Security Prompt: The ValidateAntiForgeryToken attribute helps block "Cross-Site Request Forgery" attacks. It needs to write an Html. AntiForgeryToken () Statement in the View. You will see it later.

The Bind attribute is a method to prevent Over-Posting ). For example, suppose that the Student object contains a Srcret attribute, and you don't want to let the website get its value.

  public class Student    {        public int ID { get; set; }        public string LastName { get; set; }        public string FirstMidName { get; set; }        public DateTime EnrollmentDate { get; set; }        public string Secret { get; set; }        public virtual ICollection<Enrollment> Enrollments { get; set; }
}

Even if you don't haveSecretField on the web page, a hacker cocould use a tool such asfiddler, or write some JavaScript, to postSecretForm value. Without the Bind attribute limiting the fields that the model binder uses when it createsStudentInstance,The model binder wocould pick up thatSecretForm value and use it to createStudentEntity instance. Then whatever value the hacker specified forSecretForm field wocould be updated in your database. The following image shows the fiddler tool addingSecret Field (with the value "OverPost") to the posted form values.

Even if you have no Secret field in your website, hackers can Post a Secret value through a tool such as fiddler or write Javascript. When creating a Student object, when the model is bound, there is no Bind attribute restriction field. This model binding will actually find the Secret value and use it to create the Student instance. then, no matter what value the hacker has specified, it will be updated to your database.

An alternative way to prevent overposting that is preferrred by using developers is to use view models rather than entity classes with model binding. include only the properties you want to update in the view model. once the MVC model binder has finished, copy the view model properties to the entity instance, optionally using a tool such as AutoMapper. use db. entry on the entity instance to set its state to Unchanged, and then set Property ("PropertyName "). isModified to true on each entity property that is stored in the view model. this method works in both edit and create scenarios.

Another method that many programmers welcome is to use view models instead of entity classes to bind models to prevent repeated Post operations. Include the attributes you want to update to the view model. Once the MVC model is bound, assign the attributes in the view model to the instance of the object. A tool is usually selected, for example, Automapper, modify the state of the object to unchanged, and set the IsModified attribute of the attribute to True. This method is valid during editing and creation.

Other thanBindAttribute,try-catchBlock is the only change you 've made to the scaffolded code. if an exception that derives from DataException is caught while the changes are being saved, a generic error message is displayed. dataException exceptions are sometimes caused by something external to the application rather than a programming error, so the user is advised to try again. although not implemented in this sample, a production quality application wocould log the exception. for more information, seeLog for insightSection in Monitoring and Telemetry (Building Real-World Cloud Apps with Azure ).

PS: if it is not important, it will not be translated ..

Update the Edit HttpPost Method -- Update the editing Method

InControllers \ StudentController. cs,HttpGet EditMethod (the one withoutHttpPostAttribute) usesFindMethod to retrieve the selectedStudentEntity, as you saw inDetailsMethod. You don't need to change this method.

In the controller, Find the Edit Method (get method). It uses the Find method to retrieve the selected Student object, as you can see in the Details method, you do not need to change this method.

However, replaceHttpPost EditAction method with the following code :,

Use the following method to replace the Post-based Edit Method:

[HttpPost, ActionName ("Edit")] [ValidateAntiForgeryToken] public ActionResult EditPost (int? Id) {if (id = null) {return new HttpStatusCodeResult (HttpStatusCode. badRequest);} var studentTOUpdate = db. students. find (id); if (TryUpdateModel (studentTOUpdate, "", new string [] {"LastName", "FirstName", "EnrollmentDate"}) {try {db. saveChanges (); return RedirectToAction ("Index");} catch (DataException/* dex */) {ModelState. addModelError ("", "cannot be saved, please try again") ;}} return View (studentTOUpdate );}

These changes implement a security best practice to prevent overposting, The scaffolder generatedBindAttribute and added the entity created by the model binder to the entity set with a Modified flag. That code is no longer recommended becauseBindAttribute clears out any pre-existing data in fields not listed inIncludeParameter. In the future, the MVC controller scaffolder will be updated so that it doesn't generateBindAttributes for Edit methods.

These modifications implement a security mechanism to prevent repeated Post. This framework generates the Bind attribute, adds the entity created by model binding, and sets a Modified flag for it, this code is no longer recommended. Because of the Bind attribute, all existing data in the list of parameters that are no longer included will be cleared. In the future, the MVC Framework will be upgraded, the Bind attribute is not generated for the Edit Method.

The new code reads the existing entity and calltryupdatemodel to update fields from user input in the posted form data. the Entity Framework's automatic change tracking sets the Modified flag on the entity. when the SaveChangesmethod is called,ModifiedFlag causes the Entity Framework to create SQL statements to update the database row. concurrency conflicts are ignored, and all columns of the database row are updated, including those that the user didn't change. (A later tutorial shows how to handle concurrency conflicts, and if you only want individual fields to be updated in the database, you can set the entity to Unchanged and set individual fields to Modified .)

As a best practice to prevent overposting, the fields that you want to be updateable by the Edit page are whitelisted inTryUpdateModelParameters. currently there are no extra fields that you're protecting, but listing the fields that you want the model binder to bind ensures that if you add fields to the data model in the future, they're automatically protected until you explicitly add them here.

As a result of these changes, the method signature of the HttpPost Edit method is the same as the HttpGet edit method; therefore you 've renamed the method EditPost.

 

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.