"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Examining the Edit Methods and Edit View

by Rick Anderson

[!NOTE] An updated version of this tutorial is available here that uses ASP.NET MVC 5 and Visual Studio 2013. It’s more secure, much simpler to follow and demonstrates more features.

In this section, you’ll examine the generated action methods and views for the movie controller. Then you’ll add a custom search page.

Run the application and browse to the Movies controller by appending /Movies to the URL in the address bar of your browser. Hold the mouse pointer over an Edit link to see the URL that it links to.

EditLink_sm
EditLink_sm

The Edit link was generated by the Html.ActionLink method in the Views.cshtml view:

[!code-cshtmlMain]

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

Html.ActionLink
Html.ActionLink

The Html object is a helper that’s exposed using a property on the System.Web.Mvc.WebViewPage base class. The ActionLink method of the helper makes it easy to dynamically generate HTML hyperlinks that link to action methods on controllers. The first argument to the ActionLink method is the link text to render (for example, <a>Edit Me</a>). The second argument is the name of the action method to invoke. The final argument is an anonymous object that generates the route data (in this case, the ID of 4).

The generated link shown in the previous image is http://localhost:xxxxx/Movies/Edit/4. The default route (established in App_Start.cs) takes the URL pattern {controller}/{action}/{id}. Therefore, ASP.NET translates http://localhost:xxxxx/Movies/Edit/4 into a request to the Edit action method of the Movies controller with the parameter ID equal to 4. Examine the following code from the App_Start.cs file.

[!code-csharpMain]

   1:  public static void RegisterRoutes(RouteCollection routes)
   2:  {
   3:      routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
   4:   
   5:      routes.MapRoute(
   6:          name: "Default",
   7:          url: "{controller}/{action}/{id}",
   8:          defaults: new { controller = "Home", action = "Index", 
   9:              id = UrlParameter.Optional }
  10:      );
  11:  }

You can also pass action method parameters using a query string. For example, the URL http://localhost:xxxxx/Movies/Edit?ID=4 also passes the parameter ID of 4 to the Edit action method of the Movies controller.

EditQueryString
EditQueryString

Open the Movies controller. The two Edit action methods are shown below.

[!code-csharpMain]

   1:  //
   2:  // GET: /Movies/Edit/5
   3:   
   4:  public ActionResult Edit(int id = 0)
   5:  {
   6:      Movie movie = db.Movies.Find(id);
   7:      if (movie == null)
   8:      {
   9:          return HttpNotFound();
  10:      }
  11:      return View(movie);
  12:  }
  13:   
  14:  //
  15:  // POST: /Movies/Edit/5
  16:   
  17:  [HttpPost]
  18:  public ActionResult Edit(Movie movie)
  19:  {
  20:      if (ModelState.IsValid)
  21:      {
  22:          db.Entry(movie).State = EntityState.Modified;
  23:          db.SaveChanges();
  24:          return RedirectToAction("Index");
  25:      }
  26:      return View(movie);
  27:  }

Notice the second Edit action method is preceded by the HttpPost attribute. This attribute specifies that that overload of the Edit method can be invoked only for POST requests. You could apply the HttpGet attribute to the first edit method, but that’s not necessary because it’s the default. (We’ll refer to action methods that are implicitly assigned the HttpGet attribute as HttpGet methods.)

The HttpGet Edit method takes the movie ID parameter, looks up the movie using the Entity Framework Find method, and returns the selected movie to the Edit view. The ID parameter specifies a default value of zero if the Edit method is called without a parameter. If a movie cannot be found, HttpNotFound is returned. When the scaffolding system created the Edit view, it examined the Movie class and created code to render <label> and <input> elements for each property of the class. The following example shows the Edit view that was generated:

[!code-cshtmlMain]

   1:  @model MvcMovie.Models.Movie
   2:   
   3:  @{
   4:      ViewBag.Title = "Edit";
   5:  }
   6:   
   7:  <h2>Edit</h2>
   8:   
   9:  @using (Html.BeginForm()) {
  10:      @Html.ValidationSummary(true)
  11:   
  12:      <fieldset>
  13:          <legend>Movie</legend>
  14:   
  15:          @Html.HiddenFor(model => model.ID)
  16:   
  17:          <div class="editor-label">
  18:              @Html.LabelFor(model => model.Title)
  19:          </div>
  20:          <div class="editor-field">
  21:              @Html.EditorFor(model => model.Title)
  22:              @Html.ValidationMessageFor(model => model.Title)
  23:          </div>
  24:   
  25:          <div class="editor-label">
  26:              @Html.LabelFor(model => model.ReleaseDate)
  27:          </div>
  28:          <div class="editor-field">
  29:              @Html.EditorFor(model => model.ReleaseDate)
  30:              @Html.ValidationMessageFor(model => model.ReleaseDate)
  31:          </div>
  32:   
  33:          <div class="editor-label">
  34:              @Html.LabelFor(model => model.Genre)
  35:          </div>
  36:          <div class="editor-field">
  37:              @Html.EditorFor(model => model.Genre)
  38:              @Html.ValidationMessageFor(model => model.Genre)
  39:          </div>
  40:   
  41:          <div class="editor-label">
  42:              @Html.LabelFor(model => model.Price)
  43:          </div>
  44:          <div class="editor-field">
  45:              @Html.EditorFor(model => model.Price)
  46:              @Html.ValidationMessageFor(model => model.Price)
  47:          </div>
  48:   
  49:          <p>
  50:              <input type="submit" value="Save" />
  51:          </p>
  52:      </fieldset>
  53:  }
  54:   
  55:  <div>
  56:      @Html.ActionLink("Back to List", "Index")
  57:  </div>
  58:   
  59:  @section Scripts {
  60:      @Scripts.Render("~/bundles/jqueryval")
  61:  }

Notice how the view template has a @model MvcMovie.Models.Movie statement at the top of the file — this specifies that the view expects the model for the view template to be of type Movie.

The scaffolded code uses several helper methods to streamline the HTML markup. The Html.LabelFor helper displays the name of the field (“Title”, “ReleaseDate”, “Genre”, or “Price”). The Html.EditorFor helper renders an HTML <input> element. The Html.ValidationMessageFor helper displays any validation messages associated with that property.

Run the application and navigate to the /Movies URL. Click an Edit link. In the browser, view the source for the page. The HTML for the form element is shown below.

[!code-htmlMain]

   1:  <form action="/Movies/Edit/4" method="post">    <fieldset>
   2:          <legend>Movie</legend>
   3:   
   4:          <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="4" />
   5:   
   6:          <div class="editor-label">
   7:              <label for="Title">Title</label>
   8:          </div>
   9:          <div class="editor-field">
  10:              <input class="text-box single-line" id="Title" name="Title" type="text" value="Rio Bravo" />
  11:              <span class="field-validation-valid" data-valmsg-for="Title" data-valmsg-replace="true"></span>
  12:          </div>
  13:   
  14:          <div class="editor-label">
  15:              <label for="ReleaseDate">ReleaseDate</label>
  16:          </div>
  17:          <div class="editor-field">
  18:              <input class="text-box single-line" data-val="true" data-val-date="The field ReleaseDate must be a date." data-val-required="The ReleaseDate field is required." id="ReleaseDate" name="ReleaseDate" type="text" value="4/15/1959 12:00:00 AM" />
  19:              <span class="field-validation-valid" data-valmsg-for="ReleaseDate" data-valmsg-replace="true"></span>
  20:          </div>
  21:   
  22:          <div class="editor-label">
  23:              <label for="Genre">Genre</label>
  24:          </div>
  25:          <div class="editor-field">
  26:              <input class="text-box single-line" id="Genre" name="Genre" type="text" value="Western" />
  27:              <span class="field-validation-valid" data-valmsg-for="Genre" data-valmsg-replace="true"></span>
  28:          </div>
  29:   
  30:          <div class="editor-label">
  31:              <label for="Price">Price</label>
  32:          </div>
  33:          <div class="editor-field">
  34:              <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="2.99" />
  35:              <span class="field-validation-valid" data-valmsg-for="Price" data-valmsg-replace="true"></span>
  36:          </div>
  37:   
  38:          <p>
  39:              <input type="submit" value="Save" />
  40:          </p>
  41:      </fieldset>
  42:  </form>

The <input> elements are in an HTML <form> element whose action attribute is set to post to the /Movies/Edit URL. The form data will be posted to the server when the Edit button is clicked.

Processing the POST Request

The following listing shows the HttpPost version of the Edit action method.

[!code-csharpMain]

   1:  [HttpPost] 
   2:  public ActionResult Edit(Movie movie)  
   3:  { 
   4:      if (ModelState.IsValid)  
   5:      { 
   6:          db.Entry(movie).State = EntityState.Modified; 
   7:          db.SaveChanges(); 
   8:          return RedirectToAction("Index"); 
   9:      } 
  10:      return View(movie); 
  11:  }

The ASP.NET MVC model binder takes the posted form values and creates a Movie object that’s passed as the movie parameter. The ModelState.IsValid method verifies that the data submitted in the form can be used to modify (edit or update) a Movie object. If the data is valid, the movie data is saved to the Movies collection of the db(MovieDBContext instance). The new movie data is saved to the database by calling the SaveChanges method of MovieDBContext. After saving the data, the code redirects the user to the Index action method of the MoviesController class, which displays the of movie collection, including the changes just made.

If the posted values aren’t valid, they are redisplayed in the form. The Html.ValidationMessageFor helpers in the Edit.cshtml view template take care of displaying appropriate error messages.

abcNotValid
abcNotValid

[!NOTE] to support jQuery validation for non-English locales that use a comma (“,”) for a decimal point, you must include globalize.js and your specific cultures/globalize.cultures.js file(from https://github.com/jquery/globalize ) and JavaScript to use Globalize.parseFloat. The following code shows the modifications to the Views.cshtml file to work with the “fr-FR” culture:

[!code-cshtmlMain]

   1:  @section Scripts {
   2:      @Scripts.Render("~/bundles/jqueryval")
   3:      <script src="~/Scripts/globalize.js"></script>
   4:      <script src="~/Scripts/globalize.culture.fr-FR.js"></script>
   5:      <script>
   6:          $.validator.methods.number = function (value, element) {
   7:              return this.optional(element) ||
   8:                  !isNaN(Globalize.parseFloat(value));
   9:          }
  10:          $(document).ready(function () {
  11:              Globalize.culture('fr-FR');
  12:          });
  13:      </script>
  14:      <script>
  15:          jQuery.extend(jQuery.validator.methods, {    
  16:              range: function (value, element, param) {        
  17:                  //Use the Globalization plugin to parse the value        
  18:                  var val = $.global.parseFloat(value);
  19:                  return this.optional(element) || (
  20:                      val >= param[0] && val <= param[1]);
  21:              }
  22:          });
  23:   
  24:      </script>
  25:  }

The decimal field may require a comma, not a decimal point. As a temporary fix, you can add the globalization element to the projects root web.config file. The following code shows the globalization element with the culture set to United States English.

[!code-xmlMain]

   1:  <system.web>
   2:      <globalization culture ="en-US" />
   3:      <!--elements removed for clarity-->
   4:    </system.web>

All the HttpGet methods follow a similar pattern. They get a movie object (or list of objects, in the case of Index), and pass the model to the view. The Create method passes an empty movie object to the Create view. All the methods that create, edit, delete, or otherwise modify data do so in the HttpPost overload of the method. Modifying data in an HTTP GET method is a security risk, as described in the blog post entry ASP.NET MVC Tip #46 – Don’t use Delete Links because they create Security Holes. Modifying data in a GET method also violates HTTP best practices and the architectural REST pattern, which specifies that GET requests should not change the state of your application. In other words, performing a GET operation should be a safe operation that has no side effects and doesn’t modify your persisted data.

Adding a Search Method and Search View

In this section you’ll add a SearchIndex action method that lets you search movies by genre or name. This will be available using the /Movies/SearchIndex URL. The request will display an HTML form that contains input elements that a user can enter in order to search for a movie. When a user submits the form, the action method will get the search values posted by the user and use the values to search the database.

Displaying the SearchIndex Form

Start by adding a SearchIndex action method to the existing MoviesController class. The method will return a view that contains an HTML form. Here’s the code:

[!code-csharpMain]

   1:  public ActionResult SearchIndex(string searchString) 
   2:  {           
   3:      var movies = from m in db.Movies 
   4:                   select m; 
   5:   
   6:      if (!String.IsNullOrEmpty(searchString)) 
   7:      { 
   8:          movies = movies.Where(s => s.Title.Contains(searchString)); 
   9:      } 
  10:   
  11:      return View(movies); 
  12:  }

The first line of the SearchIndex method creates the following LINQ query to select the movies:

[!code-csharpMain]

   1:  var movies = from m in db.Movies 
   2:               select m;

The query is defined at this point, but hasn’t yet been run against the data store.

If the searchString parameter contains a string, the movies query is modified to filter on the value of the search string, using the following code:

[!code-csharpMain]

   1:  if (!String.IsNullOrEmpty(searchString)) 
   2:  { 
   3:      movies = movies.Where(s => s.Title.Contains(searchString)); 
   4:  }

The s => s.Title code above is a Lambda Expression. Lambdas are used in method-based LINQ queries as arguments to standard query operator methods such as the Where method used in the above code. LINQ queries are not executed when they are defined or when they are modified by calling a method such as Where or OrderBy. Instead, query execution is deferred, which means that the evaluation of an expression is delayed until its realized value is actually iterated over or the ToList method is called. In the SearchIndex sample, the query is executed in the SearchIndex view. For more information about deferred query execution, see Query Execution.

Now you can implement the SearchIndex view that will display the form to the user. Right-click inside the SearchIndex method and then click Add View. In the Add View dialog box, specify that you’re going to pass a Movie object to the view template as its model class. In the Scaffold template list, choose List, then click Add.

AddSearchView
AddSearchView

When you click the Add button, the Views.cshtml view template is created. Because you selected List in the Scaffold template list, Visual Studio automatically generated (scaffolded) some default markup in the view. The scaffolding created an HTML form. It examined the Movie class and created code to render <label> elements for each property of the class. The listing below shows the Create view that was generated:

[!code-cshtmlMain]

   1:  @model IEnumerable<MvcMovie.Models.Movie> 
   2:   
   3:  @{ 
   4:      ViewBag.Title = "SearchIndex"; 
   5:  } 
   6:   
   7:  <h2>SearchIndex</h2> 
   8:   
   9:  <p> 
  10:      @Html.ActionLink("Create New", "Create") 
  11:  </p> 
  12:  <table> 
  13:      <tr> 
  14:          <th> 
  15:              Title 
  16:          </th> 
  17:          <th> 
  18:              ReleaseDate 
  19:          </th> 
  20:          <th> 
  21:              Genre 
  22:          </th> 
  23:          <th> 
  24:              Price 
  25:          </th> 
  26:          <th></th> 
  27:      </tr> 
  28:   
  29:  @foreach (var item in Model) { 
  30:      <tr> 
  31:          <td> 
  32:              @Html.DisplayFor(modelItem => item.Title) 
  33:          </td> 
  34:          <td> 
  35:              @Html.DisplayFor(modelItem => item.ReleaseDate) 
  36:          </td> 
  37:          <td> 
  38:              @Html.DisplayFor(modelItem => item.Genre) 
  39:          </td> 
  40:          <td> 
  41:              @Html.DisplayFor(modelItem => item.Price) 
  42:          </td> 
  43:          <td> 
  44:              @Html.ActionLink("Edit", "Edit", new { id=item.ID }) | 
  45:              @Html.ActionLink("Details", "Details", new { id=item.ID }) | 
  46:              @Html.ActionLink("Delete", "Delete", new { id=item.ID }) 
  47:          </td> 
  48:      </tr> 
  49:  } 
  50:   
  51:  </table>

Run the application and navigate to /Movies/SearchIndex. Append a query string such as ?searchString=ghost to the URL. The filtered movies are displayed.

SearchQryStr
SearchQryStr

If you change the signature of the SearchIndex method to have a parameter named id, the id parameter will match the {id} placeholder for the default routes set in the Global.asax file.

[!code-jsonMain]

   1:  {controller}/{action}/{id}

The original SearchIndex method looks like this::

[!code-csharpMain]

   1:  public ActionResult SearchIndex(string searchString) 
   2:  {           
   3:      var movies = from m in db.Movies 
   4:                   select m; 
   5:   
   6:      if (!String.IsNullOrEmpty(searchString)) 
   7:      { 
   8:          movies = movies.Where(s => s.Title.Contains(searchString)); 
   9:      } 
  10:   
  11:      return View(movies); 
  12:  }

The modified SearchIndex method would look as follows:

[!code-csharpMain]

   1:  public ActionResult SearchIndex(string id) 
   2:  { 
   3:      string searchString = id; 
   4:      var movies = from m in db.Movies 
   5:                   select m; 
   6:   
   7:      if (!String.IsNullOrEmpty(searchString)) 
   8:      { 
   9:          movies = movies.Where(s => s.Title.Contains(searchString)); 
  10:      } 
  11:   
  12:      return View(movies); 
  13:  }

You can now pass the search title as route data (a URL segment) instead of as a query string value.

SearchRouteData
SearchRouteData

However, you can’t expect users to modify the URL every time they want to search for a movie. So now you you’ll add UI to help them filter movies. If you changed the signature of the SearchIndex method to test how to pass the route-bound ID parameter, change it back so that your SearchIndex method takes a string parameter named searchString:

[!code-csharpMain]

   1:  public ActionResult SearchIndex(string searchString) 
   2:  {           
   3:       var movies = from m in db.Movies 
   4:                    select m; 
   5:   
   6:      if (!String.IsNullOrEmpty(searchString)) 
   7:      { 
   8:          movies = movies.Where(s => s.Title.Contains(searchString)); 
   9:      } 
  10:   
  11:      return View(movies); 
  12:  }

Open the Views.cshtml file, and just after @Html.ActionLink("Create New", "Create"), add the following:

[!code-cshtmlMain]

   1:  @using (Html.BeginForm()){    
   2:           <p> Title: @Html.TextBox("SearchString")<br />  
   3:           <input type="submit" value="Filter" /></p> 
   4:          }

The following example shows a portion of the Views.cshtml file with the added filtering markup.

[!code-cshtmlMain]

   1:  @model IEnumerable<MvcMovie.Models.Movie> 
   2:   
   3:  @{ 
   4:      ViewBag.Title = "SearchIndex"; 
   5:  } 
   6:   
   7:  <h2>SearchIndex</h2> 
   8:   
   9:  <p> 
  10:      @Html.ActionLink("Create New", "Create") 
  11:       
  12:       @using (Html.BeginForm()){    
  13:           <p> Title: @Html.TextBox("SearchString") <br />   
  14:           <input type="submit" value="Filter" /></p> 
  15:          } 
  16:  </p>

The Html.BeginForm helper creates an opening <form> tag. The Html.BeginForm helper causes the form to post to itself when the user submits the form by clicking the Filter button.

Run the application and try searching for a movie.

There’s no HttpPost overload of the SearchIndex method. You don’t need it, because the method isn’t changing the state of the application, just filtering data.

You could add the following HttpPost SearchIndex method. In that case, the action invoker would match the HttpPost SearchIndex method, and the HttpPost SearchIndex method would run as shown in the image below.

[!code-csharpMain]

   1:  [HttpPost] 
   2:  public string SearchIndex(FormCollection fc, string searchString) 
   3:  { 
   4:      return "<h3> From [HttpPost]SearchIndex: " + searchString + "</h3>"; 
   5:  }

SearchPostGhost
SearchPostGhost

However, even if you add this HttpPost version of the SearchIndex method, there’s a limitation in how this has all been implemented. Imagine that you want to bookmark a particular search or you want to send a link to friends that they can click in order to see the same filtered list of movies. Notice that the URL for the HTTP POST request is the same as the URL for the GET request (localhost:xxxxx/Movies/SearchIndex) – there’s no search information in the URL itself. Right now, the search string information is sent to the server as a form field value. This means you can’t capture that search information to bookmark or send to friends in a URL.

The solution is to use an overload of BeginForm that specifies that the POST request should add the search information to the URL and that it should be routed to the HttpGet version of the SearchIndex method. Replace the existing parameterless BeginForm method with the following:

[!code-cshtmlMain]

   1:  @using (Html.BeginForm("SearchIndex","Movies",FormMethod.Get))

BeginFormPost_SM
BeginFormPost_SM

Now when you submit a search, the URL contains a search query string. Searching will also go to the HttpGet SearchIndex action method, even if you have a HttpPost SearchIndex method.

SearchIndexWithGetURL
SearchIndexWithGetURL

Adding Search by Genre

If you added the HttpPost version of the SearchIndex method, delete it now.

Next, you’ll add a feature to let users search for movies by genre. Replace the SearchIndex method with the following code:

[!code-csharpMain]

   1:  public ActionResult SearchIndex(string movieGenre, string searchString) 
   2:  { 
   3:      var GenreLst = new List<string>(); 
   4:   
   5:      var GenreQry = from d in db.Movies 
   6:                     orderby d.Genre 
   7:                     select d.Genre; 
   8:      GenreLst.AddRange(GenreQry.Distinct()); 
   9:      ViewBag.movieGenre = new SelectList(GenreLst); 
  10:   
  11:      var movies = from m in db.Movies 
  12:                   select m; 
  13:   
  14:      if (!String.IsNullOrEmpty(searchString)) 
  15:      { 
  16:          movies = movies.Where(s => s.Title.Contains(searchString)); 
  17:      } 
  18:   
  19:      if (string.IsNullOrEmpty(movieGenre)) 
  20:          return View(movies); 
  21:      else 
  22:      { 
  23:          return View(movies.Where(x => x.Genre == movieGenre)); 
  24:      } 
  25:   
  26:  }

This version of the SearchIndex method takes an additional parameter, namely movieGenre. The first few lines of code create a List object to hold movie genres from the database.

The following code is a LINQ query that retrieves all the genres from the database.

[!code-csharpMain]

   1:  var GenreQry = from d in db.Movies 
   2:                     orderby d.Genre 
   3:                     select d.Genre;

The code uses the AddRange method of the generic List collection to add all the distinct genres to the list. (Without the Distinct modifier, duplicate genres would be added — for example, comedy would be added twice in our sample). The code then stores the list of genres in the ViewBag object.

The following code shows how to check the movieGenre parameter. If it’s not empty, the code further constrains the movies query to limit the selected movies to the specified genre.

[!code-csharpMain]

   1:  if (string.IsNullOrEmpty(movieGenre)) 
   2:          return View(movies); 
   3:  else 
   4:  { 
   5:      return View(movies.Where(x => x.Genre == movieGenre)); 
   6:  }

Adding Markup to the SearchIndex View to Support Search by Genre

Add an Html.DropDownList helper to the Views.cshtml file, just before the TextBox helper. The completed markup is shown below:

[!code-cshtmlMain]

   1:  <p> 
   2:      @Html.ActionLink("Create New", "Create") 
   3:      @using (Html.BeginForm("SearchIndex","Movies",FormMethod.Get)){     
   4:           <p>Genre: @Html.DropDownList("movieGenre", "All")   
   5:             Title: @Html.TextBox("SearchString")   
   6:           <input type="submit" value="Filter" /></p> 
   7:          } 
   8:  </p>

Run the application and browse to /Movies/SearchIndex. Try a search by genre, by movie name, and by both criteria.

In this section you examined the CRUD action methods and views generated by the framework. You created a search action method and view that let users search by movie title and genre. In the next section, you’ll look at how to add a property to the Movie model and how to add an initializer that will automatically create a test database.

Previous Next



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/mvc/overview/older-versions/getting-started-with-aspnet-mvc4/examining-the-edit-methods-and-edit-view.htm
< THANKS ME>