C# 无法访问控制器中带有参数的操作方法
这是我的EmployeeController,我不明白为什么我可以访问url作为Employee/Index/1C# 无法访问控制器中带有参数的操作方法,c#,asp.net,asp.net-mvc,C#,Asp.net,Asp.net Mvc,这是我的EmployeeController,我不明白为什么我可以访问url作为Employee/Index/1 namespace MVCDemo.Controllers { public class EmployeeController : Controller { public ActionResult index(int departmentId) { EmployeeContext employeeContext
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/1//为什么它不起作用?这和细节动作法不一样吗
/员工/详细信息/1//已工作
/Employee/Index?departmentId=1//已工作,但为什么/Index/1不工作查找配置路由的代码。最有可能的是,Visual Studio为您生成了一些代码,并将其放在方法RouteConfig.RegisterRoutes中 列表中的第三项将映射到名为id的参数。为方法参数选择的名称很重要:asp.net mvc将使用反射检测参数名称,并将这些名称与路由配置中设置的值相匹配 如果将索引方法中的参数名称更改为id:
然后id将与MapRoute中引用的名称匹配,您的代码将起作用。查找配置路由的代码。最有可能的是,Visual Studio为您生成了一些代码,并将其放在方法RouteConfig.RegisterRoutes中 列表中的第三项将映射到名为id的参数。为方法参数选择的名称很重要:asp.net mvc将使用反射检测参数名称,并将这些名称与路由配置中设置的值相匹配 如果将索引方法中的参数名称更改为id:
然后id将匹配MapRoute中引用的名称,您的代码将正常工作。我假设您没有更改RouteConfig.cs 要使员工/Index/1正常工作,您需要具备:
public class EmployeeController : Controller
{
// Employee/Index/1
public ActionResult Index(int id)
{
EmployeeContext employeeContext = new EmployeeContext();
List<Employee> employee = employeeContext.Employees.Where(emp => emp.DepartmentId == departmentId).ToList();
return View(employee);
}
}
顺便说一句:你说/Department/Details/1//工作了。我猜你的意思是/Employee/Details/1//worked我假设你没有改变RouteConfig.cs 要使员工/Index/1正常工作,您需要具备:
public class EmployeeController : Controller
{
// Employee/Index/1
public ActionResult Index(int id)
{
EmployeeContext employeeContext = new EmployeeContext();
List<Employee> employee = employeeContext.Employees.Where(emp => emp.DepartmentId == departmentId).ToList();
return View(employee);
}
}
顺便说一句:你说/Department/Details/1//工作了。我猜您的意思是/Employee/Details/1//workedEmployee/Index/1只有在参数名为id时才起作用 因此,您的操作方法必须如下所示:
public ActionResult index(int id)
当然,您可以尝试更改默认的routingcontrollerName/actionName/idEmployee/Index/1,仅当您的参数名为id时才起作用 因此,您的操作方法必须如下所示:
public ActionResult index(int id)
当然,您可以尝试更改默认路由控制器名称/actionName/id如果您正在猜测,这意味着您不确定问题出在哪里-在本例中,当您到达50+代表时发表评论。请解释为什么不建议更改路由-这样做在ASP.Net MVC中是非常常见的活动。在目前的情况下,这是一个奇怪的建议,因此这篇文章应该被否决。这是我在这个网站上的第一个答案,好的,我用我在下一句中使用“必须”这个词的方式更改了它。我不建议更改默认路由,因为默认路由在大多数情况下已经足够了,尝试更改它通常只会浪费时间。如果你在猜测某件事,这意味着你不确定问题出在哪里——在这种情况下,当你得到消息时,请发表评论请解释为什么不建议更改路由-在ASP.Net MVC中,这样做是非常经常的活动。在目前的情况下,这是一个奇怪的建议,因此这篇文章应该被否决。这是我在这个网站上的第一个答案,好的,我用我在下一句中使用“必须”这个词的方式改变了它。我不建议改变默认路由,因为默认路由在大多数情况下已经足够了,试图改变它通常只会浪费时间。