ASP. net mvc 5-Edit method and Edit view)

Source: Internet
Author: User
Tags actionlink

In this section, you will verify the Edit action methods and view generated by the movie controller. However, we will first modify the code to make the release date attribute look better. OpenModels \ Movie. csFile, and add the highlighted lines as follows:

using System;using System.ComponentModel.DataAnnotations;using System.Data.Entity;namespace MvcMovie.Models{public class Movie{public int ID { get; set; }public string Title { get; set; }[Display(Name = "Release Date")][DataType(DataType.Date)][DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]public DateTime ReleaseDate { get; set; }public string Genre { get; set; }public decimal Price { get; set; }}public class MovieDBContext : DbContext{public DbSet
 
   Movies { get; set; }}}
 

In the next tutorial, we will discuss DataAnnotations. The Display attribute specifies the name of the field to be displayed (in this example, "Release Date" is used instead of "ReleaseDate "). The DataType attribute is used to specify the type of data. In this example, it is a date, so the time details stored in this field are not displayed. The DisplayFormat attribute has a bug in Chrome: The displayed date format is incorrect.

Append/Movies to the address bar of your browser and navigate to the Movies page. And enterEdit)Page.

Edit)The link is composedViews \ Movies \ Index. cshtmlView

Generated by the Html. ActionLink method in

@ Html. ActionLink ("Edit", "Edit", new {id = item. ID })

HtmlThe object is a Helper and is made public on the base class of System. Web. Mvc. WebViewPage in the form of attributes. ActionLink is a help method (Helper) that allows you to dynamically generate HTML hyperlink to the operation method in the Controller.ActionLinkThe first parameter of the method is the link text to be rendered (for example,Edit Me). The second parameter is the name of the operation method to be called (in this example, the Edit Method ). The last parameter is an anonymous object used to generate route data (in this example, ID 4 ).

The generated link is http: // localhost: xxxxx/Movies/Edit/4..The default routeApp_Start \ RouteConfig. cs) The URL matching mode is as follows:{controller}/{action}/{id}. Therefore, ASP. NETHttp: // localhost: xxxxx/Movies/Edit/4ConvertMoviesControllerEditOperation Method and ParametersIDRequest equal to 4. ViewApp_Start \ RouteConfig. csFile.

The MapRoute method uses the HTTP request route to find the correct controller and action method, and provides the optional ID parameter. The MapRoute method is also used to generate a URL through the HtmlHelpers such as ActionLink controller, operation method, and any route data.

public static void RegisterRoutes(RouteCollection routes){routes.IgnoreRoute("{resource}.axd/{*pathInfo}");routes.MapRoute(name: "Default",url: "{controller}/{action}/{id}",defaults: new { controller = "Home", action = "Index",id = UrlParameter.Optional });}

You can also use QueryString to pass the parameters of the operation method. For example, URL:Http: // localhost: xxxxx/Movies/Edit? ID = 3The ParameterIDSend 3 requestsMoviesControllerEditOperation Method.

OpenMoviesController. The following twoEditOperation Method.

// GET: /Movies/Edit/5public ActionResult Edit(int? id){if (id == null){return new HttpStatusCodeResult(HttpStatusCode.BadRequest);}Movie movie = db.Movies.Find(id);if (movie == null){return HttpNotFound();}return View(movie);}// POST: /Movies/Edit/5// To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598.[HttpPost][ValidateAntiForgeryToken]public ActionResult Edit([Bind(Include="ID,Title,ReleaseDate,Genre,Price")] Movie movie){if (ModelState.IsValid){db.Entry(movie).State = EntityState.Modified;db.SaveChanges();return RedirectToAction("Index");}return View(movie);}

Note: The secondEditThe operation method has the HttpPost attribute. This attribute specifiesEditMethod. This method is only called by the POST request. You can apply the HttpGet attribute to the first editing method, but this is unnecessary because it is the default attribute. (The operation method is implicitly specifiedHttpGetAttribute to actHttpGetMethod .) Bind attributes are another important security mechanism that can prevent hacker attacks (from over-posting data to your model ). You should include only the bind Property and want to change it. You can read the related information in my overposting security note. We will use a simple model in this tutorial to bind all data to the model. The ValidateAntiForgeryToken attribute is used to prevent forged requests and pair with the @ Html. AntiForgeryToken () file (Views \ Movies \ Edit. cshtml), As shown in, some of the view files are being edited:

@model MvcMovie.Models.Movie@{ViewBag.Title = "Edit";}Edit@using (Html.BeginForm()){@Html.AntiForgeryToken()Movie
 @Html.ValidationSummary(true)@Html.HiddenFor(model => model.ID)@Html.LabelFor(model => model.Title, new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.Title)@Html.ValidationMessageFor(model => model.Title)

@ Html. AntiForgeryToken () to generate a hidden form. The anti-counterfeit token must match the Edit Method of the Movies controller. In my tutorial XSRF/CSRF Prevention in MVC, you can read

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.