c# - ASP.NET MVC - 将参数传递给 Controller

标签 c# asp.net-mvc

我有一个 Controller ,其操作方法如下:

public class InventoryController : Controller
{
    public ActionResult ViewStockNext(int firstItem)
    {
        // Do some stuff
    }
}

当我运行它时,我收到一条错误消息:

The parameters dictionary does not contain a valid value of type 'System.Int32' for parameter 'firstItem'. To make a parameter optional its type should either be a reference type or a Nullable type.

我曾经让它工作过,我决定尝试不带参数的函数。发现 Controller 不是持久的,我把参数放回去,现在当我调用方法时它拒绝识别参数。

我正在使用此 url 语法来调用操作:

http://localhost:2316/Inventory/ViewStockNext/11

知道为什么我会收到此错误以及我需要做些什么来修复它吗?

我已经尝试添加另一个方法,该方法接受一个整数到类中,但它也因同样的原因而失败。我尝试添加一个接受字符串的字符串,并将该字符串设置为空。我试过添加一个不带参数的,效果很好,但当然不适合我的需要。

最佳答案

您的路由需要按照 {controller}/{action}/{firstItem} 行设置。如果您在 global.asax.cs 文件中将路由保留为默认 {controller}/{action}/{id},那么您需要传入 id.

routes.MapRoute(
    "Inventory",
    "Inventory/{action}/{firstItem}",
    new { controller = "Inventory", action = "ListAll", firstItem = "" }
);

...或类似的东西。

关于c# - ASP.NET MVC - 将参数传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/155864/

相关文章:

c# - 在模型中动态设置正则表达式

c# - 有没有办法从 COM Interop 调用 C# 委托(delegate)?

c# - 在 C 中引发和处理事件

c# - WinRT 中的多语言应用程序名称

c# - 将数据从 View 传递到 Controller

单击按钮时,javascript 函数未定义错误

c# - 在给定复杂继承的情况下保持一致的松散耦合

c# - 在不同的窗口检测 WM_MOUSEMOVE

c# - 使用 MVVM 模式将项目添加到数据绑定(bind)列表框的最佳方法?

c# - 具有 ASP.Net 成员资格提供程序登录问题的 MVC 3 应用程序