发布于 2016-06-21 09:53:34 | 143 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的精品教程,程序狗速度看过来!

ASP.NET

ASP.NET 是.NET FrameWork的一部分,是一项微软公司的技术,是一种使嵌入网页中的脚本可由因特网服务器执行的服务器端脚本技术,它可以在通过HTTP请求文档时再在Web服务器上动态创建它们。 指 Active Server Pages(动态服务器页面) ,运行于 IIS(Internet Information Server 服务,是Windows开发的Web服务器)之中的程序 。


本文主要演示如何修改控制器和视图以及处理POST的请求,以达到实现我们想要的功能。

在本节中,您将开始修改为电影控制器所新加的操作方法和视图。然后,您将添加一个自定义的搜索页。

在浏览器地址栏里追加/Movies, 浏览到Movies页面。并进入编辑(Edit)页面。

Edit(编辑)链接是由Views\Movies\Index.cshtml视图中的Html.ActionLink方法所生成的:


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

Html对象是一个Helper, 以属性的形式, 在System.Web.Mvc.WebViewPage基类上公开。 ActionLink是一个帮助方法,便于动态生成指向Controller中操作方法的HTML 超链接链接。ActionLink方法的第一个参数是想要呈现的链接文本 (例如,<a>Edit Me</a>)。第二个参数是要调用的操作方法的名称。最后一个参数是一个匿名对象,用来生成路由数据 (在本例中,ID 为 4 的)。

在上图中所生成的链接是http://localhost:xxxxx/Movies/Edit/4默认的路由 (在App_Start\RouteConfig.cs 中设定) 使用的 URL 匹配模式为: {controller}/{action}/{id}。因此,ASP.NET 将http://localhost:xxxxx/Movies/Edit/4转化到Movies 控制器中Edit操作方法,参数ID等于 4 的请求。查看App_Start\RouteConfig.cs文件中的以下代码。


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 }
   );

}

您还可以使用QueryString来传递操作方法的参数。例如,URL: http://localhost:xxxxx/Movies/Edit?ID=4还会将参数ID为 4的请求传递给Movies控制器的Edit操作方法。

打开Movies控制器。如下所示的两个Edit操作方法。


//

// GET: /Movies/Edit/5



public ActionResult Edit(int id = 0)

{
   Movie movie = db.Movies.Find(id);
   if (movie == null)
   {
     return HttpNotFound();
   }
   return View(movie);

}



//

// POST: /Movies/Edit/5



[HttpPost]

public ActionResult Edit(Movie movie)

{
   if (ModelState.IsValid)
   {
     db.Entry(movie).State = EntityState.Modified;
     db.SaveChanges();
     return RedirectToAction("Index");
   }
   return View(movie);

}

注意,第二个Edit操作方法的上面有HttpPost属性。此属性指定了Edit方法的重载,此方法仅被POST 请求所调用。您可以将HttpGet属性应用于第一个编辑方法,但这是不必要的,因为它是默认的属性。(操作方法会被隐式的指定为HttpGet属性,从而作为HttpGet方法。)

HttpGet Edit方法会获取电影ID参数、 查找影片使用Entity Framework 的Find方法,并返回到选定影片的编辑视图。如果不带参数调用Edit 方法,ID 参数被指定为默认值 零。如果找不到一部电影,则返回HttpNotFound 。当VS自动创建编辑视图时,它会查看Movie类并为类的每个属性创建用于Render的<label>和<input>的元素。下面的示例为自动创建的编辑视图:


@model MvcMovie.Models.Movie



@{
   ViewBag.Title = "Edit";

}



<h2>Edit</h2>



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


   <fieldset>
     <legend>Movie</legend>


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


     <div class="editor-label">
       @Html.LabelFor(model => model.Title)
     </div>
     <div class="editor-field">
       @Html.EditorFor(model => model.Title)
       @Html.ValidationMessageFor(model => model.Title)
     </div>


     <div class="editor-label">
       @Html.LabelFor(model => model.ReleaseDate)
     </div>
     <div class="editor-field">
       @Html.EditorFor(model => model.ReleaseDate)
       @Html.ValidationMessageFor(model => model.ReleaseDate)
     </div>


     <div class="editor-label">
       @Html.LabelFor(model => model.Genre)
     </div>
     <div class="editor-field">
       @Html.EditorFor(model => model.Genre)
       @Html.ValidationMessageFor(model => model.Genre)
     </div>


     <div class="editor-label">
       @Html.LabelFor(model => model.Price)
     </div>
     <div class="editor-field">
       @Html.EditorFor(model => model.Price)
       @Html.ValidationMessageFor(model => model.Price)
     </div>


     <p>
       <input type="submit" value="Save" />
     </p>
   </fieldset>

}



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

</div>



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

}

注意,视图模板在文件的顶部有 @model MvcMovie.Models.Movie 的声明,这将指定视图期望的模型类型为Movie。

自动生成的代码,使用了Helper方法的几种简化的 HTML 标记。 Html.LabelFor 用来显示字段的名称("Title"、"ReleaseDate"、"Genre"或"Price")。 Html.EditorFor 用来呈现 HTML <input>元素。Html.ValidationMessageFor 用来显示与该属性相关联的任何验证消息。

运行该应用程序,然后浏览URL,/Movies。单击Edit链接。在浏览器中查看页面源代码。HTML Form中的元素如下所示:


<form action="/Movies/Edit/4" method="post">  <fieldset>
     <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="4" />


     <div class="editor-label">
       <label for="Title">Title</label>
     </div>
     <div class="editor-field">
       <input class="text-box single-line" id="Title" name="Title" type="text" value="Rio Bravo" />
       <span class="field-validation-valid" data-valmsg-for="Title" data-valmsg-replace="true"></span>
     </div>


     <div class="editor-label">
       <label for="ReleaseDate">ReleaseDate</label>
     </div>
     <div class="editor-field">
       <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" />
       <span class="field-validation-valid" data-valmsg-for="ReleaseDate" data-valmsg-replace="true"></span>
     </div>


     <div class="editor-label">
       <label for="Genre">Genre</label>
     </div>
     <div class="editor-field">
       <input class="text-box single-line" id="Genre" name="Genre" type="text" value="Western" />
       <span class="field-validation-valid" data-valmsg-for="Genre" data-valmsg-replace="true"></span>
     </div>


     <div class="editor-label">
       <label for="Price">Price</label>
     </div>
     <div class="editor-field">
       <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" />
       <span class="field-validation-valid" data-valmsg-for="Price" data-valmsg-replace="true"></span>
     </div>


     <p>
       <input type="submit" value="Save" />
     </p>
   </fieldset>

</form>

被<form> HTML 元素所包括的 <input> 元素会被发送到,form的action属性所设置的URL:/Movies/Edit。单击Edit按钮时,from数据将会被发送到服务器。

处理 POST 请求

下面的代码显示了Edit操作方法的HttpPost处理:


[HttpPost] 

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 模型绑定 接收form所post的数据,并转换所接收的movie请求数据从而创建一个Movie对象。ModelState.IsValid方法用于验证提交的表单数据是否可用于修改(编辑或更新)一个Movie对象。如果数据是有效的电影数据,将保存到数据库的Movies集合(MovieDBContext instance)。通过调用MovieDBContext的SaveChanges方法,新的电影数据会被保存到数据库。数据保存之后,代码会把用户重定向到MoviesController类的Index操作方法,页面将显示电影列表,同时包括刚刚所做的更新。

如果form发送的值不是有效的值,它们将重新显示在form中。Edit.cshtml视图模板中的Html.ValidationMessageFor Helper将用来显示相应的错误消息。

注意,为了使jQuery支持使用逗号的非英语区域的验证 ,需要设置逗号(",")来表示小数点,你需要引入globalize.js并且你还需要具体的指定cultures/globalize.cultures.js文件 (地址在https://github.com/jquery/globalize) 在 JavaScript 中可以使用 Globalize.parseFloat。下面的代码展示了在"FR-FR" Culture下的 Views\Movies\Edit.cshtml 视图:


@section Scripts {
   @Scripts.Render("~/bundles/jqueryval")
   <script src="~/Scripts/globalize.js"></script>
   <script src="~/Scripts/globalize.culture.fr-FR.js"></script>
   <script>
     $.validator.methods.number = function (value, element) {
       return this.optional(element) ||
         !isNaN(Globalize.parseFloat(value));
     }
     $(document).ready(function () {
       Globalize.culture('fr-FR');
     });
   </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>

}

十进制字段可能需要逗号,而不是小数点。作为临时的修复,您可以向项目根 web.config 文件添加的全球化设置。下面的代码演示设置为美国英语的全球化文化设置。


<system.web>
   <globalization culture ="en-US" />
   <!--elements removed for clarity-->
</system.web>

所有HttpGet方法都遵循类似的模式。它们获取影片对象 (或对象集合,如Index里的对象集合),并将模型传递给视图。Create方法将一个空的Movie对象传递给创建视图。创建、 编辑、 删除或以其它方式修改数据的方法都是HttpPost方法。使用HTTP GET 方法来修改数据是存在安全风险,在ASP.NET MVC Tip #46 – Don't use Delete Links because they create Security Holes的Blog中有完整的叙述。在 GET 方法中修改数据还违反了 HTTP 的最佳做法和Rest架构模式, GET 请求不应更改应用程序的状态。换句话说,执行 GET 操作,应该是一种安全的操作,没有任何副作用,不会修改您持久化的数据。

添加一个搜索方法和搜索视图

在本节中,您将添加一个搜索电影流派或名称的SearchIndex操作方法。这将可使用/Movies/SearchIndex URL。该请求将显示一个 HTML 表单,其中包含输入的元素,用户可以输入一部要搜索的电影。当用户提交窗体时,操作方法将获取用户输入的搜索条件并在数据库中搜索。

显示 SearchIndex 窗体

通过将SearchIndex操作方法添加到现有的MoviesController类开始。该方法将返回一个视图包含一个 HTML 表单。如下代码:


public ActionResult SearchIndex(string searchString) 

{      
   var movies = from m in db.Movies 
         select m; 
 
   if (!String.IsNullOrEmpty(searchString)) 
   { 
     movies = movies.Where(s => s.Title.Contains(searchString)); 
   } 
 
   return View(movies); 

}

SearchIndex方法的第一行创建以下的LINQ查询,以选择看电影:


var movies = from m in db.Movies 
         select m;

查询在这一点上,只是定义,并还没有执行到数据上。

如果searchString参数包含一个字符串,可以使用下面的代码,修改电影查询要筛选的搜索字符串:


if (!String.IsNullOrEmpty(searchString)) 
{ 
  movies = movies.Where(s => s.Title.Contains(searchString)); 
}

上面s => s.Title 代码是一个Lambda 表达式。Lambda 是基于方法的LINQ查询,(例如上面的where查询)在上面的代码中使用了标准查询参数运算符的方法。当定义LINQ查询或修改查询条件时(如调用Where 或OrderBy方法时,不会执行 LINQ 查询。相反,查询执行会被延迟,这意味着表达式的计算延迟,直到取得实际的值或调用ToList方法。在SearchIndex示例中,SearchIndex 视图中执行查询。有关延迟的查询执行的详细信息,请参阅Query Execution.

现在,您可以实现SearchIndex视图并将其显示给用户。在SearchIndex方法内单击右键,然后单击添加视图。在添加视图对话框中,指定你要将Movie对象传递给视图模板作为其模型类。在框架模板列表中,选择列表,然后单击添加.

当您单击添加按钮时,创建了Views\Movies\SearchIndex.cshtml视图模板。因为你选中了框架模板的列表,Visual Studio 将自动生成列表视图中的某些默认标记。框架模版创建了 HTML 表单。它会检查Movie类,并为类的每个属性创建用来展示的<label>元素。下面是生成的视图:


@model IEnumerable<MvcMovie.Models.Movie> 
 

@{ 
   ViewBag.Title = "SearchIndex"; 

} 
 

<h2>SearchIndex</h2> 
 

<p> 
   @Html.ActionLink("Create New", "Create") 

</p> 

<table> 
   <tr> 
     <th> 
       Title 
     </th> 
     <th> 
       ReleaseDate 
     </th> 
     <th> 
       Genre 
     </th> 
     <th> 
       Price 
     </th> 
     <th></th> 
   </tr> 
 

@foreach (var item in Model) { 
   <tr> 
     <td> 
       @Html.DisplayFor(modelItem => item.Title) 
     </td> 
     <td> 
       @Html.DisplayFor(modelItem => item.ReleaseDate) 
     </td> 
     <td> 
       @Html.DisplayFor(modelItem => item.Genre) 
     </td> 
     <td> 
       @Html.DisplayFor(modelItem => item.Price) 
     </td> 
     <td> 
       @Html.ActionLink("Edit", "Edit", new { id=item.ID }) | 
       @Html.ActionLink("Details", "Details", new { id=item.ID }) | 
       @Html.ActionLink("Delete", "Delete", new { id=item.ID }) 
     </td> 
   </tr> 

} 
 

</table>

运行该应用程序,然后转到 /Movies/SearchIndex。追加查询字符串到URL如?searchString=ghost。显示已筛选的电影。

如果您更改SearchIndex方法的签名,改为参数id,在Global.asax文件中设置的默认路由将使得: id参数将匹配{id}占位符。

{controller}/{action}/{id}

原来的SearchIndex方法看起来是这样的:


public ActionResult SearchIndex(string searchString) 

{      
   var movies = from m in db.Movies 
         select m; 
 
   if (!String.IsNullOrEmpty(searchString)) 
   { 
     movies = movies.Where(s => s.Title.Contains(searchString)); 
   } 
 
   return View(movies); 

}

修改后的SearchIndex方法将如下所示:


public ActionResult SearchIndex(string id) 

{ 
   string searchString = id; 
   var movies = from m in db.Movies 
         select m; 
 
   if (!String.IsNullOrEmpty(searchString)) 
   { 
     movies = movies.Where(s => s.Title.Contains(searchString)); 
   } 
 
   return View(movies); 

}

您现在可以将搜索标题作为路由数据 (部分URL) 来替代QueryString。

但是,每次用户想要搜索一部电影时, 你不能指望用户去修改 URL。所以,现在您将添加 UI页面,以帮助他们去筛选电影。如果您更改了的SearchIndex方法来测试如何传递路由绑定的 ID 参数,更改它,以便您的SearchIndex方法采用字符串searchString参数:


public ActionResult SearchIndex(string searchString) 

{      
   var movies = from m in db.Movies 
          select m; 
 
   if (!String.IsNullOrEmpty(searchString)) 
   { 
     movies = movies.Where(s => s.Title.Contains(searchString)); 
   } 
 
   return View(movies); 

}

打开Views\Movies\SearchIndex.cshtml文件,并在 @Html.ActionLink("Create New", "Create")后面,添加以下内容:


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

下面的示例展示了添加后, Views\Movies\SearchIndex.cshtml 文件的一部分:


@model IEnumerable<MvcMovie.Models.Movie> 
 

@{ 
   ViewBag.Title = "SearchIndex"; 

} 
 

<h2>SearchIndex</h2> 
 

<p> 
   @Html.ActionLink("Create New", "Create") 
   
   @using (Html.BeginForm()){  
     <p> Title: @Html.TextBox("SearchString") <br />  
     <input type="submit" value="Filter" /></p> 
     } 

</p>

Html.BeginForm Helper创建开放<form>标记。Html.BeginForm Helper将使得, 在用户通过单击筛选按钮提交窗体时,窗体Post本Url。运行该应用程序,请尝试搜索一部电影。

SearchIndex没有HttpPost 的重载方法。你并不需要它,因为该方法并不更改应用程序数据的状态,只是筛选数据。

您可以添加如下的HttpPost SearchIndex 方法。在这种情况下,请求将进入HttpPost SearchIndex方法, HttpPost SearchIndex方法将返回如下图的内容。


[HttpPost] 

public string SearchIndex(FormCollection fc, string searchString) 

{ 
   return "<h3> From [HttpPost]SearchIndex: " + searchString + "</h3>"; 

}

但是,即使您添加此HttpPost SearchIndex 方法,这一实现其实是有局限的。想象一下您想要添加书签给特定的搜索,或者您想要把搜索链接发送给朋友们,他们可以通过单击看到一样的电影搜索列表。请注意 HTTP POST 请求的 URL 和GET 请求的URL 是相同的(localhost:xxxxx/电影/SearchIndex)— — 在 URL 中没有搜索信息。现在,搜索字符串信息作为窗体字段值,发送到服务器。这意味着您不能在 URL 中捕获此搜索信息,以添加书签或发送给朋友。

解决方法是使用重载的BeginForm ,它指定 POST 请求应添加到 URL 的搜索信息,并应该路由到 HttpGet SearchIndex 方法。将现有的无参数BeginForm 方法,修改为以下内容:


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

现在当您提交搜索,该 URL 将包含搜索的查询字符串。搜索还会请求到 HttpGet SearchIndex操作方法,即使您也有一个HttpPost SearchIndex方法。

按照电影流派添加搜索

如果您添加了HttpPost 的SearchIndex方法,请立即删除它。

接下来,您将添加功能可以让用户按流派搜索电影。将SearchIndex方法替换成下面的代码:


public ActionResult SearchIndex(string movieGenre, string searchString) 

{ 
   var GenreLst = new List<string>(); 
 
   var GenreQry = from d in db.Movies 
          orderby d.Genre 
          select d.Genre; 
   GenreLst.AddRange(GenreQry.Distinct()); 
   ViewBag.movieGenre = new SelectList(GenreLst); 
 
   var movies = from m in db.Movies 
         select m; 
 
   if (!String.IsNullOrEmpty(searchString)) 
   { 
     movies = movies.Where(s => s.Title.Contains(searchString)); 
   } 
 
   if (string.IsNullOrEmpty(movieGenre)) 
     return View(movies); 
   else 
   { 
     return View(movies.Where(x => x.Genre == movieGenre)); 
   } 
 

}

这版的SearchIndex方法将接受一个附加的movieGenre参数。前几行的代码会创建一个List对象来保存数据库中的电影流派。

下面的代码是从数据库中检索所有流派的 LINQ 查询。


var GenreQry = from d in db.Movies 
          orderby d.Genre 
          select d.Genre;

该代码使用泛型 List集合的 AddRange方法将所有不同的流派,添加到集合中的。(使用 Distinct修饰符,不会添加重复的流派 -- 例如,在我们的示例中添加了两次喜剧)。该代码然后在ViewBag对象中存储了流派的数据列表。

下面的代码演示如何检查movieGenre参数。如果它不是空的,代码进一步指定了所查询的电影流派。


if (string.IsNullOrEmpty(movieGenre)) 
  return View(movies); 
else 
{ 
  return View(movies.Where(x => x.Genre == movieGenre)); 
}

在SearchIndex 视图中添加选择框支持按流派搜索

在TextBox Helper之前添加 Html.DropDownList Helper到Views\Movies\SearchIndex.cshtml文件中。添加完成后,如下面所示:


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

</p>

运行该应用程序并浏览 /Movies/SearchIndex。按流派、 按电影名,或者同时这两者,来尝试搜索。

在这一节中您修改了CRUD 操作方法和框架所生成的视图。您创建了一个搜索操作方法和视图,让用户可以搜索电影标题和流派。在下一节中,您将看到如何将属性添加到Movie模型,以及如何添加一个初始设定并自动创建一个测试数据库。



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务