这是我的 EmployeeController,我不明白为什么我可以访问 url 作为 Employee/Index/1
namespace MVCDemo.Controllers
{
public class EmployeeController : Controller
{
public ActionResult index(int departmentId)
{
EmployeeContext employeeContext = new EmployeeContext();
List<Employee> employee = employeeContext.Employees.Where(emp => emp.DepartmentId == departmentId).ToList();
return View(employee);
}
public ActionResult Details(int id)
{
EmployeeContext employeeContext = new EmployeeContext();
Employee employee = employeeContext.Employees.Single(emp => emp.EmployeeId == id);
return View(employee);
}
}
}
/Employee/Index//当然不行,很公平,
/Employee/Index/1//为什么不起作用?不是和details action方法一样吗?
/Employee/Details/1//工作过
/Employee/Index?departmentId=1//有效但为什么/Index/1 无效
最佳答案
找到配置路由的代码。很可能,Visual Studio 为您生成了一些代码并将其放入方法 RouteConfig.RegisterRoutes
中。
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
列表中的第三项将被映射到名为 id
的参数。您为方法参数选择的名称很重要:asp.net mvc 将使用反射来检测您的参数名称,并将这些名称与路由配置中设置的值相匹配。
如果您将 index
方法中的参数名称更改为 id
:
public ActionResult Index(int id)
{
...
}
然后 id
将匹配 MapRoute
中引用的名称,您的代码将起作用。
关于c# - 无法访问 Controller 中带参数的操作方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41670232/