考虑一个使用Area约定的ASP.NET MVC 1.0项目,如Nov. 2008 Phil Haack blog post所述。这个解决方案一旦设置就可以正常工作!
由于我对ASP.NET MVC路由规则的了解有限,我的麻烦就开始了。
我的目的是创建一个像这样的动作方法和URL结构:
http://mysite/Animals/Dogs/ViewDog/Buster
DogsController.ViewDog()
看起来像这样:
public ActionResult ViewDog(string dogName)
{
if (dogName!= null)
{
var someDog = new DogFormViewModel(dogName); //snip a bunch more
return View(someDog);
}
else { return View("DogNotFound"); }
}
手头的任务是确保RegisterRoutes()
具有正确的条目。
更新
这是映射的新路线:
routes.MapRoute("ViewDog", "Animals/{controller}/{action}/{dogName}",
new { controller = "Dogs",
action = "ViewDog", dogName = "" });
创建了URL的链接:
<%= Html.RouteLink("Brown Buster", "ViewDog", new RouteValueDictionary(new { controller="Dogs", action="ViewDog", dogName="Buster" }))%>
按预期创建URL。感谢Craig Stuntz and his blog post on Html.RouteLink
。
http://mySite/Animals/Dogs/ViewDog/Buster
新问题:参数dogName
未从网址中提取字符串值“Buster”。对方法的调用成功,但参数的计算结果为null。
问题
你怎么能:
int id
? 我想将参数的名称更改为int
。 答案 0 :(得分:1)
您确定ActionLink实际上与您向他们展示问题的路线相匹配吗?如果您有多个路线,我强烈建议您使用RouteLink而不是ActionLink as I explain in great detail in this post。当您使用RouteLink时,您不可能匹配错误的路线,至少在URL生成中是这样。
答案 1 :(得分:0)
默认参数“id”不必是int。它将匹配您在action方法中声明的任何类型。为什么不这样做呢?
public ActionResult ViewDog(string id)
{
if (id!= null)
{
var someDog = new DogFormViewModel(id); //snip a bunch more
return View(someDog);
}
else { return View("DogNotFound"); }
}