ASP.NET MVC 學習4、Controller中添加SearchIndex頁面,實現簡單的查詢功能


參考:http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/examining-the-edit-methods-and-edit-view

本文內容:

1,熟悉MVC的路由過程,URL如果導向到Controller相應的方法中

2,新增SearchIndex頁面,實現簡單的查詢功能

 

http://localhost:9898/Movies鼠標移動到”Edit”上面的時候,我們看到Edit將要導向的路徑

這個路徑對應的HTML代碼是: @Html.ActionLink("Edit", "Edit", new { id = item.ID })

參數說明:第一個參數linkText鏈接文字,第二個參數是需要調用的action 方法,第三個參數是匿名對象(anonymous object)生成路由數據:

HTML對象的ActionLink method 動態生成(dynamically genetate)HTML鏈接指向Controller中的 action methods.

 http://localhost:9898/movies/Edit/1 這個url路徑,asp.net會根據MVC中默認的路由配置(App_Start\RouteConfig.cs)按照{controller}/{action}/{id}的格式進行導向:{movies}/{Edit}/{1}    默認路由配置:

public class RouteConfig
{
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 }
);
}
}
View Code

如果我們更新URL:http://localhost:9898/Movies/Edit?ID=1 這個URL同樣可以根據ActionResult方法導向到剛才的Edit頁面,然后查看Controller中的Edit方法:

 //點擊"Edit"時會調用下面的這個Edit方法,傳遞過來ID,返回對應的Movie
//默認的ID參數為0
public ActionResult Edit(int id = 0)
{
Movie movie = db.Movies.Find(id);
if (movie == null)
{
return HttpNotFound();
}
return View(movie);
}
//
// POST: /Movies/Edit/5
//點擊"Save"按鈕,處理頁面的post請求
        [HttpPost]
public ActionResult Edit(Movie movie)
{
//
            if (ModelState.IsValid)
{
db.Entry(movie).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(movie);
}
View Code

我們注意到ActionResult 方法上面有[HttpPost],這個HttpPost的意思是:只有頁面的Post請求會調用這個方法。如果方法前面沒有加[HttpPost],默認為[HttpGet]表示方法在Get請求的時候被調用

這里補一下GetPost方法:

1. get是從服務器上獲取數據,post是向服務器傳送數據。
2. get是把參數數據隊列加到提交表單的ACTION屬性所指的URL中,值和表單內各個字段一一對應,在URL中可以看到。post是通過HTTP post機制,將表單內各個字段與其內容放置在HTML HEADER內一起傳送到ACTION屬性所指的URL地址。用戶看不到這個過程。
3. 對於get方式,服務器端用Request.QueryString獲取變量的值,對於post方式,服務器端用Request.Form獲取提交的數據。
4. get傳送的數據量較小,不能大於2KB。post傳送的數據量較大,一般被默認為不受限制。但理論上,IIS4中最大量為80KB,IIS5中為100KB。
5. get安全性非常低,post安全性較高。但是執行效率卻比Post方法好。
建議:
1、get方式的安全性較Post方式要差些,包含機密信息的話,建議用Post數據提交方式;
2、在做數據查詢時,建議用Get方式;而在做數據添加、修改或刪除時,建議用Post方式

 

 

ActionRestlt方法對應的.cshtml頁面中@model MvcMovie.Models.Movie 指明view template中的Model是 Movie。我們來看一下幾個View中的Helper方法:

Html.LabelFor  helper顯示了字段名稱("Title", "ReleaseDate", "Genre", or "Price").

Html.EditorFor helper 加載了HTML <input>元素

Html.ValidationMessageFor helper顯示其對應屬性的驗證信息

點擊”Save”時,<input> submit會提交一條post數據到 /Movies/Edit URL form中的數據傳遞到Server

處理POST請求:

 

  //點擊"Save"按鈕,處理頁面的post請求
        [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 model binder接收頁面提交的form數據並把數據新建為Movie 對象,作為ActionResult Edit(Movie movie)的參數。

 

ModelState.IsValid 方法,會檢查提交過來的數據是否可以進行edit or update,如果數據是有效的,movies數據就會保存到MovieDBContext的實例中(db)。 MovieDBContext SaveChanges方法把數據保存到數據庫。保存以后頁面重定向到index頁面

如果保存的數據是無效的,不符合規則的,Html.ValidationMessageFor 提示錯誤信息

Note:為了支持非英文地區在Decimal數字中輸入逗號," ,Edit.cshtml 添加以下js :  globalize JS下載

@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>
View Code

webconfig中添加:

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

所有的HttpGet方法都是類似的。他們得到一個Movie對象,然后傳遞給View,Get:不應該改變頁面中的數據

 

下面我們添加查詢頁面 ,Adding a Search Method and Search View

1,Controller中添加SearchIndex方法():

  public ActionResult SearchIndex(string MovieGenre, string SearchString)
{
var GenreLst = new List<string>();
//Select All Genre
var GenreQry = from d in db.Movies
orderby d.Genre
select d.Genre;
GenreLst.AddRange(GenreQry.Distinct());
ViewBag.MovieGenre = new SelectList(GenreLst); // 把List傳遞給ViewBag
var movies = from m in db.Movies
select m;
//SearchString 字符串如果不為空,Movies filter 包含SearchString的對象
if (!string.IsNullOrEmpty(SearchString))
{
movies = movies.Where(s => s.Title.Contains(SearchString));
}
if (string.IsNullOrEmpty(MovieGenre))
//如果MovieGenre為空,直接返回movies
return View(movies);
else
{
//Movie不為空,filter Genre
return View(movies.Where(x => x.Genre == MovieGenre));
}
}

 

2,SearchIndex方法中右鍵點擊,添加視圖

 3,SearchIndex.cshtml頁面中添加以下代碼:

  @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>
}

4,查詢頁面實現:

 

查詢頁面的,需要熟悉的東西:Linq語句查詢,參數傳遞,View中HTML Helper中TextBoxt,DropDownList等控件的書寫

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM