ASP.NET MVC 5 tutorial: Edit method and the Edit view.

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

In this section, the Edit method and the view we continue to study the generation. But in the study before, we first release date look better. Open the Models\Movie.cs file, add the following line yellow background:

The code in listing 1:Models\Movie.cs file

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)]
        public DateTime ReleaseDate { get; set; }
        public string Genre { get; set; }
        public decimal Price { get; set; }
    }

    public class MovieDBContext : DbContext
    {
        public DbSet<Movie> Movies { get; set; }
    }
}

We will introduce DataAnnotations in the next section. The Display attribute specifies the field name display (“ in the case of the Release Date” replaced the “ ReleaseDate”). The DataType property specifies the data type, in this case it is the type of date, so the time information stored in the field will not be displayed.

Run the application, the addition of /movies to access the Movies controller in the browser address bar. The mouse on the Edit link above, it links to.:

Figure 1: see Edit link address

image

Edit links are generated by the Html.ActionLink method, in the Views\Movies\Index.cshtml view, as shown in the following code example:

The code in listing 2:Html.ActionLink method

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

The 2:Html.ActionLink method

image

The Html object is a property of the System.Web.Mvc.WebViewPage in the base class, ActionLink method makes the method for dynamic generation of the controller of the HTML hyperlink is more simple. The first parameter to the ActionLink method is to display the link text (such as <a> Edit Me</a>); the second parameter is the controller of the method to call (here is the Edit method); the last one is the generation of an anonymous object routing data used (here is ID, value is 1).

In generating the address indicated in Figure 1 is http://localhost:2264/Movies/Edit/1 . The default route matching {controller}/{action}/{id} URL model . Therefore, ASP.NET will request address translation of http://localhost:2264/Movies/Edit/1 as Edit MoviesController, ID parameters for the 1. To view the App_Start\RouteConfig.cs code in the file:

The code in Listing 3: the default routing rules

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

You can also use the query string parameters, such as http://localhost:xxxxx/Movies/Edit? ID=1 parameters can also be ID 1 values are passed to the Movies controller.

Figure 3: pass through query string parameters

image

Open the Movies controller, it contains two Edit method, the code as follows:

The code in Listing 4: MoviesController.cs two Edit method

//
// GET: /Movies/Edit/5
public ActionResult Edit(Int32 id)
{
    Movie movie = db.Movies.Find(id);
    if (movie == null)
    {
        return HttpNotFound();
    }
    return View(movie);
}

//
// POST: /Movies/Edit/5

[HttpPost

]
[ValidateAntiForgeryToken]
public ActionResult Edit(Movie movie)
{
    if (ModelState.IsValid)
    {
        db.Entry(movie).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(movie);
}

Note that the second Edit methods, it is the characteristics of HttpPost modified (yellow background code label), Edit only the POST request to call this overloaded the characteristics specified. We can add HttpGet properties for the first Edit method, but this is not necessary, because it is the default value (we will not labeled as HttpGet method). The second Edit methods and characteristics of a ValidateAntiForgeryToken, this property is used to prevent bogus requests, it and view (Views\Movies\Edit.cshtml) in the @Html.AntiForgeryToken () come in pairs.

The code in listing 5:@Html.AntiForgeryToken ().

@model MvcMovie.Models.Movie

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset class="form-horizontal">
        <legend>Movie</legend>

        @Html.HiddenFor(model => model.ID)

        <div class="control-group">
            @Html.LabelFor(model => model.Title, new { @class = "control-label" })
            <div class="controls">
                @Html.EditorFor(model => model.Title)
                @Html.ValidationMessageFor(model => model.Title, null, new { @class = "help-inline" })
            </div>
        </div>

@Html.AntiForgeryToken() Create a form anti-counterfeiting mark, must match the Edit method in MoviesController.

The parameter Edit HttpGet labeling method receives a ID, by Entity Framework Find method to find the movie, and will find the results returned a Edit view. If the call to the Edit method with no parameters, the value of the ID parameter will be the default 0. If the movie information is not found, the controller will return a HttpNotFound. When the support system to create Edit view, it will check the Movie class, create a mapping of < for each of its properties; label> <input> element code. The following example shows the Edit view code to create the Visual Studio stent system:

The code in listing 6:Edit view

@model MvcMovie.Models.Movie

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset class="form-horizontal">
        <legend>Movie</legend>

        @Html.HiddenFor(model => model.ID)

        <div class="control-group">
            @Html.LabelFor(model => model.Title, new { @class = "control-label" })
            <div class="controls">
                @Html.EditorFor(model => model.Title)
                @Html.ValidationMessageFor(model => model.Title, null, new { @class = "help-inline" })
            </div>
        </div>

        <div class="control-group">
            @Html.LabelFor(model => model.ReleaseDate, new { @class = "control-label" })
            <div class="controls">
                @Html.EditorFor(model => model.ReleaseDate)
                @Html.ValidationMessageFor(model => model.ReleaseDate, null, new { @class = "help-inline" })
            </div>
        </div>

        <div class="control-group">
            @Html.LabelFor(model => model.Genre, new { @class = "control-label" })
            <div class="controls">
                @Html.EditorFor(model => model.Genre)
                @Html.ValidationMessageFor(model => model.Genre, null, new { @class = "help-inline" })
            </div>
        </div>

        <div class="control-group">
            @Html.LabelFor(model => model.Price, new { @class = "control-label" })
            <div class="controls">
                @Html.EditorFor(model => model.Price)
                @Html.ValidationMessageFor(model => model.Price, null, new { @class = "help-inline" })
            </div>
        </div>

        <div class="form-actions no-color">
            <input type="submit" value="Save" class="btn" />
        </div>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}

Specify a Movie to the view model in the view file at the top of the statement @model MvcMovie.Models.Movie.  

Support the generated code uses a lot of simplified HTML markers help method, Html.LabelFor method is used to display the field name ("Title", "ReleaseDate", "Genre", and "Price"), the Html.EditorFor method creates a HTML <input> elements, Html.ValidationMessageFor method combined with attribute display some validation information.

Run the application, navigate to the /movies address, click on the Edit link, in a web browser, view the page source code, form tags HTML code as follows:

The code in Listing 7: form label HTML code generation

<form action="/Movies/Edit/1" method="post">
    <

input name="__RequestVerificationToken" type="hidden" value="vM6-yBtYJY5uRgKm3ivFw9gLMjauE9i2-Wi6Y--2Swm4-BlucfrG71zQV3n773tT9i8ytaG5WSanfBBd54qIhAKAkTJO_Z0UhRaGPDhMJ9M1" /> <fieldset class

="form-horizontal">
        <legend>Movie</legend>

        <input data-val="true" data-val-number="The field ID must be a number." data-val-required="The ID field is required. " id="ID" name="ID" type="hidden" value="1" />

        <div class="control-group">
            <label class="control-label" for="Title">Title</label>
            <div class="controls">
                <input class="text-box single-line" id="Title" name="Title" type="text" value="Chinese partners" />
                <span class="field-validation-valid help-inline" data-valmsg-for="Title" data-valmsg-replace="true"></span>
            </div>
        </div>

        <div class="control-group">
            <label class="control-label" for="ReleaseDate">Release Date</label>
            <div class="controls">
                <input class="text-box single-line" data-val="true" data-val-date="The field Release Date must be a date." data-val-required="The Release Date field is required. " id="ReleaseDate" name="ReleaseDate" type="date" value="2013/6/18" />
                <span class="field-validation-valid help-inline" data-valmsg-for="ReleaseDate" data-valmsg-replace="true"></span>
            </div>
        </div>

        <div class="control-group">
            <label class="control-label" for="Genre">Genre</label>
            <div class="controls">
                <input class="text-box single-line" id="Genre" name="Genre" type="text" value="Self-Improvement" />
                <span class="field-validation-valid help-inline" data-valmsg-for="Genre" data-valmsg-replace="true"></span>
            </div>
        </div>

        <div class="control-group">
            <label class="control-label" for="Price">Price</label>
            <div class="controls">
                <input class="text-box single-line" data-val="true" data-val-number="The field Price must be a number." data-val-required="The Price field is required. " id="Price" name="Price" type="text" value="70.00" />
                <span class="field-validation-valid help-inline" data-valmsg-for="Price" data-valmsg-replace="true"></span>
            </div>
        </div>

        <div class="form-actions no-color">
            <input type="submit" value="Save" class="btn" />
        </div>
    </fieldset>
</form>

Look at this form tag, whose action property is /movies/edit/1, the form will be submitted to this address, but it contains <input> tags corresponding fields for each Movie class. When you click the “ Save” button, the form data will be submitted to the server. Second lines of code, I use the highlight prompt, this code is to use @Html.AntiForgeryToken () the hidden field generated, used to prevent bogus requests.

Processing the POST request

Below is the Edit method receives the POST request.:

The code in listing 8:Edit method

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Movie movie)
{
    if (ModelState.IsValid)
    {
        db.Entry(movie).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(movie);
}

ASP.NET MVC model binder to create a Movie object using the form data is submitted, passed as the movie parameter to the Edit method. ModelState.IsValid  To verify whether the form submission data can be used to modify the Movie object (edit or update), if the verification passes, movie data will be saved in the db.Movies list (DB is an instance of MovieDBContext by calling the db.SaveChanges method), the film modified data stored in the database. In the preservation of data, RedirectToAction will jump to the Index method, is used to display the list of films, the film will be able to see the information updated.

In the user input process, once the input validation values did not pass, the client will display an error message, these functions are performed by the Javascript, if you disable Javascript, client authentication will fail, but the server will check into the illegal data, then will contain error information to display in the client form. In the following chapters we will introduce more verification details.

The Html.ValidationMessageFor method in the Edit.cshtml view will display an appropriate error message. The following diagram:

Figure 4: editing the Movie authentication information

image_thumb

All the Get request processing methods have similar pattern: they get a movie object (in Index's movie list), and then passed to the View. Create method to pass an empty movie data to the view. Modify the data security risk using HTTP GET method, also violated the HTTP best practices, and clearly pointed out in REST mode, the GET request should not change the state of the application, in other words, GET operation should be a safe operation, no side effects, also won't modify the persistence of your data.

Localization of verification

If you are using English, this section can be skipped. As a Chinese national user, I put this part of translation.

For non English speaking users, the decimal comma (","), and non American date format, in order to support Jquery authentication, you must include the globalize.js and specific cultures/globalize.cultures.js file, using Globalize.parseFloat in Javascript. You can get jQuery non-English validation through NuGet (English area do not install Globalize).

From the Tools menu click Library Package Manager, and then click Manage NuGet Packages for Solution.

Click on the menu bar in “ ” > “ library package manager ” > “ management solution for NuGet package”.

Figure 5:NuGet menu

image

In the left click the “ on line &rdquo, enter in the search box;“Globalize”:

Figure 6: query Globalize installation package

image

Click the “ installation of ” button, Scripts\jquery.globalize\globalize.js file will be added to the project, the Scripts\jquery.globalize\cultures\ folder contains a lot of Javascript files.

The following code shows the file Views\Movies\Edit.cshtml using the Chinese regional changes (the original writer use French as demonstration):

The code in listing 9:script code - Edit.cshtml

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
    <script src="~/Scripts/jquery.globalize/globalize.js"></script>
    <script src="~/Scripts/jquery.globalize/cultures/globalize.culture.zh-CN.js"></script>
    <script>
        $.validator.methods.number = function (value, element) {
            return this.optional(element) ||
                !isNaN(Globalize.parseFloat(value));
        }
        $(document).ready(function () {
            Globalize.culture('zh-CN');
        });
    </script>
    <script>
        jQuery.extend(jQuery.validator.methods, {
            range: function (value, element, param) {
                //Use the Globalization plugin to parse the value
                var val = $.global.parseFloat(value);
                return this.optional(element) || (
                    val >= param[0] && val <= param[1]);
            }
        });
    </script>
    <script>
        $.validator.methods.date = function (value, element) {
            return this.optional(element) ||
            !isDate(Globalize.parseDate(value));
        }
    </script>
}

In order to avoid the edit view in each write such a piece of code, you can write them in the layout page.

In the next section we will program search function.

This paper also released the take-off in the network, the original address

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Aimee at November 17, 2013 - 2:43 PM