asp.net mvc的路由id参数 [英] asp.net mvc routing id parameter
问题描述
我的工作在asp.net的MVC网站上。我有一个路线
I am working on a website in asp.net mvc. I have a route
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
// Parameter defaults
);
这是缺省路由。我有一个方法
which is the default route. And I have a method
public ActionResult ErrorPage(int errorno)
{
return View();
}
现在,如果我要运行该code。与的http://东西/ myController的/的errorPage / 1
这是行不通的。但是,如果我从 errorno
更改参数名ID
有用。
Now if I want to run this code with http://something/mycontroller/Errorpage/1
it doesn't work. But if I change the parameter name to id from errorno
it works.
是否必须具有相同的参数名称,这种方法吗?或者,我需要为这种情况下创建单独的路线?
Is it compulsory to have same parameter name for this method? Or do I need to create separate routes for such situations?
推荐答案
所以,你有一个参数名为 errorno
,你想它从参数有一个值 ID
。这显然是绑定的问题。
So, you have a parameter named errorno
, and you want it to have a value from parameter id
. This is obviously the binding problem.
如何解决这个问题:
-
创建模型绑定的类:
create a class for model binder:
public class ParameterBinder : IModelBinder
{
public string ActualParameter { get; private set; }
public ParameterBinder(string actualParameter)
{
this.ActualParameter = actualParameter;
}
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
object id = controllerContext.RouteData.Values[this.ActualParameter];
return id;
}
}
创建自定义的模型绑定一个自定义属性:
create a custom attribute for custom model binding:
[AttributeUsage(AttributeTargets.Parameter)]
public class BindParameterAttribute : CustomModelBinderAttribute
{
public string ActualParameter { get; private set; }
public BindParameterAttribute(string actualParameter)
{
this.ActualParameter = actualParameter;
}
public override IModelBinder GetBinder()
{
return new ParameterBinder(this.ActualParameter);
}
}
应用新的属性到你的动作参数需要:
apply the new attribute to your action parameters as needed:
public ActionResult ErrorPage(
[BindParameter("id")]
int errorno)
{
return View();
}
现在你的 errorno
将具有价值,这是因为通过ID
为您的网址。
Now your errorno
will have the value, which was passed as id
for your url.
请注意:您可以删除放慢参数 ID
从上面的例子,如果你确信你需要它不仅解决了 ID
。
Note: you can remove the paramter id
from the example above, if you are sure you need it solved only for id
.
离开这种方式可以让你绑定其他参数了。
Leaving this way will allow you bind other parameters too.
这篇关于asp.net mvc的路由id参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!