0

我是 MVC 的新手,我正在尝试编辑我完成的教程以了解一切是如何工作的。最初,本教程有一个搜索功能,可让您通过两个字符串参数进行搜索,一个检查电影标题,一个检查电影类型,返回与这些参数匹配的任何值的查询。

我正在尝试进行演员搜索,该搜索按演员姓名和演员年龄(int)进行搜索。随着年龄的增长,我不断遇到不可为空的类型问题,我尝试了从将年龄声明为 int? 到 .ToString()'ing IsNullOrEmpty 的所有方法,但没有任何效果。

有人可以告诉我该怎么做吗?

下面是教程的 searchIndex 函数。(两串)

public ActionResult SearchIndex(string movieGenre, string searchString)
    {
        var GenreList = new List<String>();
        var GenreQry = from d in db.Movies orderby d.Genre select d.Genre;

        GenreList.AddRange(GenreQry.Distinct());
        ViewBag.movieGenre = new SelectList(GenreList);


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

    }

下面是我的版本(int Age 和一个字符串)

public ActionResult SearchIndex(int ageValue, string searchString)
        {
            var AgeList = new List<int>();
            var AgeListQry = from d in db.Actors orderby d.Age select d.Age;

            AgeList.AddRange(AgeListQry.Distinct());
            ViewBag.ageValue = new SelectList(AgeList);

            var actors = from a in db.Actors select a;

            if (!String.IsNullOrEmpty(searchString))
            {
                actors = actors.Where(s => s.Name.Contains(searchString));

            }

            if ("Trying to see if Age is null - this fails on page load")
            {
                return View(actors);
            }
            else
            {
                return View(actors.Where(x => x.Age == ageValue));
            }
        }

我在模型中初始化 int Age 是:

public DateTime BirthDate { get; set; }//user input
public int Age
            {
                get { 
                    return (int)(DateTime.Now - BirthDate).TotalDays / 365; 
                }

我对年龄的看法(不确定如何在此处完全实现 int

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

任何帮助将不胜感激,因为我对这一切都是全新的。

谢谢!

4

1 回答 1

0

问题是变量Age没有预制{get; set;}它是像这样手动映射的

public DateTime BirthDate { get; set; }
        public int Age
        {
            get
            {
                DateTime today = DateTime.Today;
                int age = today.Year - BirthDate.Year;
                if (BirthDate > today.AddYears(-age)) age--;
                return (int)age;
            }

        }

因此Age在表中不存在,它被认为是non-mapped,并且您必须使用不同的映射项(带有 a 的变量{get; set;})来确定您的 non-mapped 变量。

在这种情况下,我使用 BirthDate 来计算我的控制器中的年龄。

于 2014-05-20T16:55:59.570 回答