无法访问Controller中带有参数的操作方法

刻线

这是我的EmployeeController,我不明白为什么我可以以Employee / Index / 1的身份访问url

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 //为什么不起作用?与细节动作方法不一样吗?

/ 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您的代码将起作用。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

操作方法参数中的必需属性

来自分类Dev

无法访问名称中带有空格的属性

来自分类Dev

带有角度的发布请求不会从我的操作方法中返回任何内容

来自分类Dev

无法将参数从按钮传递到操作方法

来自分类Dev

带有ActionController / AsyncActionController的异步操作方法

来自分类Dev

无法访问Controller中对象的属性

来自分类Dev

无法访问Controller中的$ data值

来自分类Dev

无法访问播放框架中的参数

来自分类Dev

如何使用DbContext类中存在的DbSet <>属性作为Controller类中存在的操作方法的参数?

来自分类Dev

HttpPost操作方法中的视图模型参数为null

来自分类Dev

HttpPost操作方法中的视图模型参数为null

来自分类Dev

拦截器无法访问操作参数

来自分类Dev

NET MVC中如何使用私有操作方法?

来自分类Dev

在Django客户端测试中无法访问带有名称的网址(NoReverseMatch错误)

来自分类Dev

无法访问线程run()中的方法

来自分类Dev

无法访问组件方法中的$ refs

来自分类Dev

无法访问线程run()中的方法

来自分类Dev

无法访问Java中的Class方法

来自分类Dev

我无法访问类中的方法

来自分类Dev

流星-无法访问所有读取操作

来自分类Dev

流星-无法访问所有读取操作

来自分类Dev

尽管有策略,CloudFormation无法访问模板中的SSM参数

来自分类Dev

操作方法的参数始终为空

来自分类Dev

无法访问带有附加元素的更新状态

来自分类Dev

带有Activator的实例无法访问属性,反射

来自分类Dev

无法访问带有索引的php数组?

来自分类Dev

我的创建操作无法访问.new_record?方法

来自分类Dev

在AngularJS中使用.controller方法时无法访问$ location

来自分类Dev

View Controller无法访问Arary中的元素

Related 相关文章

热门标签

归档