我有一个工作页面,其中有多个参数,如jobType,工作负载等。 页面可能有也可能没有任何/所有参数。
路线图:
routes.MapRoute(
"JobsRoute",
url: "Jobs/Index/{workload}/{jobType}",
defaults: new { controller = "Jobs", action = "Index", workload = UrlParameter.Optional, jobType = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "PostJob", action = "Index", id = UrlParameter.Optional }
);
控制器(部分方法代码):
public ActionResult Index(string workload = "", string jobType = "")
{
SearchJobs model = new SearchJobs();
using (var context = new OutsourceEntityContext())
{
model.lstJobs = context.Jobs.ToList();
if (!workload.Equals(""))
{
int jobWorkloadKey = context.JobWorkload.Where(t => t.Name.Equals(workload)).First().Key;
model.lstJobs = model.lstJobs.Where(t => t.WorkloadKey == jobWorkloadKey).ToList();
}
}
}
我希望这样的网址能够运作:
http://localhost:51576/Jobs/workload/15-20%20hours%20per%20week
http://localhost:51576/Jobs/workload/15-20%20hours%20per%20week/jobType/Hourly
感谢您的帮助。
罗汉。
答案 0 :(得分:0)
由于您需要在网址中使用jobtype和工作负载,因此您应该在定义路由时指定。
routes.MapRoute(
name: "Jobs",
url: "Jobs/workload/{workload}",
defaults: new { controller = "Job", action = "Index",
workload = UrlParameter.Optional }
);
routes.MapRoute(
name: "JobsWithJobType",
url: "Jobs/workload/{workload}/jobtype/{jobType}",
defaults: new { controller = "Job", action = "Index",
jobType = UrlParameter.Optional}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
或者如果您想要执行属性路由方式,
在RegisterRoutes
RouteConfig.cs
方法中启用属性路由
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
//default route definition goes here
}
并使用属性路径装饰您的操作方法。
public class JobsController : Controller
{
[Route("jobs/workload/{workload}/jobtype/{jobtype?}")]
[Route("jobs/workload/{workload?}")]
[Route("jobs")]
public ActionResult Index(string workload = "", string jobType = "")
{
return View();
}
}