与MVC自定义搜索直达航线 [英] Direct route to custom search with MVC
问题描述
我需要创建一个MVC自定义路由建立一个自定义搜索:
I need to create a custom route with MVC to build a custom search:
默认主页的指数的操作:
Default Home's Index's Action:
public virtual ActionResult Index()
{
return View();
}
和我想读这样的字符串:
And I would like to read a string like this:
public virtual ActionResult Index(string name)
{
// call a service with the string name
return View();
}
有关的URL,如:
www.company.com/name
问题是,我有这两条路线,但它不工作:
The problem is that I have this two routes but it's not working:
routes.MapRoute(
name: "Name",
url: "{name}",
defaults: new { controller = "Home", action = "Index", name = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", area = "", id = UrlParameter.Optional }
);
这样一来,其他任何控制器则主页被重定向到首页,如果我切换命令,它无法找到网首页动作。
This way, any controller other then Home is redirected to Home, and if I switch the order, it can't find the Index Home Action.
推荐答案
您可以使用属性路由此。你可以看到有关包这里的细节。安装属性路由包后。现在,天则默认情况下为MVC5应用程序安装。如下更改操作方法:
You can use attribute routing for this. You can see the details about the package here. After installing the attribute routing package. Now a days it is installed by default for MVC5 application. Change your action method as below:
[GET("{name}")]
public virtual ActionResult Index(string name)
{
// call a service with the string name
return View();
}
下面是为code以上一个问题:
路由器将发送请求没有名字也该操作方法。为了避免这种情况,你可以如下更改:
Here's a catch for the code above: The router will send the requests without the name also to this action method. To avoid that, you can change it as below:
[GET("{name}")]
public virtual ActionResult Index2(string name)
{
// call a service with the string name
return View("Index");
}
这篇关于与MVC自定义搜索直达航线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!