MVC控制器中routeconfig后的调用函数
Call function after routeconfig in MVC controller
我用MVC做了路由配置。路线是这样定义的:
routes.MapRoute(
name: "Box",
url: "boxes/{id}",
defaults: new { controller = "Boxes", action = "Index", id = UrlParameter.Optional }
);
问题是当我从视图框调用 javascript 函数时,我调用的所有函数都被重定向到索引函数。
例如,如果我调用 var url = "/Boxes/ReturnPrice";
,站点不会调用此函数,而是调用索引函数。
boxesController中的index函数是这样定义的:
public ActionResult Index()
{
//Code here
return view();
}
当你调用 /Boxes/ReturnPrice
时,它匹配你的 "Box" 路由定义。该框架会将“ReturnPrice
”从url映射到id
参数!
你需要定义一个路由约束来告诉你的 id 属性 是 int 类型(我假设你的情况是 int )。您还需要确保存在通用路由定义来处理格式为 controllername/actionmethodname
.
的正常请求
您可以在使用正则表达式定义路由时定义路由约束。
routes.MapRoute(
name: "Box",
url: "boxes/{id}",
defaults: new { controller = "Boxes", action = "Index", id = UrlParameter.Optional },
constraints: new { id = @"\d+" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
使用此 Boxes/ReturnPrice
将转到 ReturnPrice 操作方法,而 Boxes/5
将转到将值 5 设置为 Id 参数的 Index 操作方法。
我用MVC做了路由配置。路线是这样定义的:
routes.MapRoute(
name: "Box",
url: "boxes/{id}",
defaults: new { controller = "Boxes", action = "Index", id = UrlParameter.Optional }
);
问题是当我从视图框调用 javascript 函数时,我调用的所有函数都被重定向到索引函数。
例如,如果我调用 var url = "/Boxes/ReturnPrice";
,站点不会调用此函数,而是调用索引函数。
boxesController中的index函数是这样定义的:
public ActionResult Index()
{
//Code here
return view();
}
当你调用 /Boxes/ReturnPrice
时,它匹配你的 "Box" 路由定义。该框架会将“ReturnPrice
”从url映射到id
参数!
你需要定义一个路由约束来告诉你的 id 属性 是 int 类型(我假设你的情况是 int )。您还需要确保存在通用路由定义来处理格式为 controllername/actionmethodname
.
您可以在使用正则表达式定义路由时定义路由约束。
routes.MapRoute(
name: "Box",
url: "boxes/{id}",
defaults: new { controller = "Boxes", action = "Index", id = UrlParameter.Optional },
constraints: new { id = @"\d+" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
使用此 Boxes/ReturnPrice
将转到 ReturnPrice 操作方法,而 Boxes/5
将转到将值 5 设置为 Id 参数的 Index 操作方法。