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();
}
现在,如果我想用 http://something/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
传递给您的 url 的值.
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屋!