传递字符串参数MVC 3

时间:2011-07-28 18:08:18

标签: entity-framework asp.net-mvc-3

我正在尝试在MVC3中传递一个字符串参数。

生成的URL是:

http://localhost:50164/Property/Browse/Oregon

这似乎是带有参数“Oregon”的函数“Browse”中的Property控制器类。

调用正确的函数,但字符串显示为空。

        public ViewResult Browse(string location)
        {
            //counted_properties: 3 counted_properties_here: 0 
            ViewData["counted_properties"] = db.Properties.Count(); // debug    3 total
            ViewData["counted_properties_here"] = db.Properties.Where(p => p.location == "Oregon").Count(); // debug    1 (the right answer!)
//return View(db.Properties.Where(p => p.location == tmp_location).ToList());     // 0 (bad!)

            ViewData["the_location"] = location;
            int size = tmp_location.Length;     // unhandled null exception when tmp_location = location
            ViewData["location_length"] = size;
     //       return View(db.Properties.Where(p => p.location == "Oregon").ToList());     // Right! but hardcoded
            return View(db.Properties.Where(p => p.location == location).ToList());
        }

当我使用硬编码字符串(Oregon)返回lambda时,我得到了正确的答案。

当我使用参数(字符串位置)返回lambda时,我得到零结果。

当我尝试显示ViewData [“the_location”]时,它是参数的直接副本,它是空白的。也许我不想尝试正确显示它。以下是我的观点:

Location: @Html.Encode(ViewData["the_location"] )

当我调用location.Length时,我得到一个未处理的null异常,但是当我在像“Oregon”这样的硬编码参数上调用Length时,这是有效的。

看起来字符串是空的,但这没有意义,因为当我到达属性/浏览功能时,我在URL中看到“Oregon”。

我开始怀疑是否允许我在MVC中传递字符串作为参数,因为我没有看到任何带字符串参数的示例。

这是未解决问题的延续:

C#/ASP.NET lambda conversion

顺便说一下,我不是想在这里推广俄勒冈州。我从来没有去过那里。也许这是一个好地方。

1 个答案:

答案 0 :(得分:1)

检查您的路由。传统上,您提供的URL会将值(“Oregon”)映射到“id”参数,而不是您尝试使用的location参数。重命名参数或更改路线以使用“{controller} / {action} / {location}”。

相关问题