ASP.NET MVC系列:为视图添加查询功能

  首先,在MoviesController里添加一个查询方法,代码如下

        public ActionResult SearchIndex(string title)
        {
            //查询数据库中的电影表
            var movies = from m in db.Movies
                         select m;

            if (!string.IsNullOrEmpty(title))
            {
                //查询包含title的电影
                movies = movies.Where(m => m.Title.Contains(title));
            }
            return View(movies);
        }

  为SearchIndex方法创建视图,并选择视图的模型类Movie和框架模板List

  添加完成视图后,我们在浏览器中输入URL地址http://localhost:60534/Movies/searchindex?title=123(我已经在数据库中添加了title=3的数据),它已经能够为我们查询数据

  现在我们在SearchIndex视图再加上一个查询按钮,通过按钮提交查询条件

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

  一个基本的查询功能就实现了

  http://www.asp.net/mvc/overview/older-versions/getting-started-with-aspnet-mvc4/examining-the-edit-methods-and-edit-view

posted @ 2016-03-24 14:44  高效养猪倌  阅读(2220)  评论(0编辑  收藏  举报