简体   繁体   中英

action method with parameter in Controller can't be accessed

This is my EmployeeController, I don't understand why I can access url as 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 //of course doesn't work, fair enough,

/Employee/Index/1 //why it doesn't work? isn't it the same as details action method?

/Employee/Details/1 //worked

/Employee/Index?departmentId=1 //worked but why /Index/1 doesn't work

Find the code where you configure the routes. Most likely, Visual Studio generated some code for you and put it in the method RouteConfig.RegisterRoutes .

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

The third item in the list will be mapped to a parameter called id . The name you choose for your method parameters is important: asp.net mvc will use reflection to detect your parameter names, and match these to values set in the route configuration.

If you changed the name of the parameter in your index method to id :

    public ActionResult Index(int id)
    {
       ...
    }

then id will match the name referenced in MapRoute , and your code will work.

I'm assuming that you have not changed RouteConfig.cs

For Employee/Index/1 to work you need to have:

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);
    }

}

Btw: You said /Department/Details/1 //worked . I guess you mean /Employee/Details/1 //worked

Employee/Index/1 works only if your parameter name is id

so your action method must be like this:

public ActionResult index(int id)

of course you can try to change the default routing(controllerName/actionName/id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM