查询功能

查询功能

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_StartRouteConfig.cs)按照{controller}/{action}/{id}的格式进行导向:{movies}/{Edit}/{1}    默认路由配置:

 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);
        }
复制代码

我们注意到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 ,globalize.culture.fr-FR.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>
复制代码

webconfig中添加:

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

所有的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等控件的书写

 
 
分类: ASP.NET MVC
标签: asp.net mvc

 
 
原文地址:https://www.cnblogs.com/Leo_wl/p/3592864.html