C# ASP.NET MVC - 将参数传递给控制器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/155864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC - passing parameters to the controller
提问by Odd
I have a controller with an action method as follows:
我有一个带有操作方法的控制器,如下所示:
public class InventoryController : Controller
{
public ActionResult ViewStockNext(int firstItem)
{
// Do some stuff
}
}
And when I run it I get an error stating:
当我运行它时,我收到一条错误消息:
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.
参数字典不包含参数“firstItem”的“System.Int32”类型的有效值。要使参数可选,其类型应该是引用类型或 Nullable 类型。
I had it working at one point and I decided to try the function without parameters. Finding out that the controller was not persistant I put the parameter back in, now it refuses to recognise the parameter when I call the method.
我曾经让它工作过,我决定尝试不带参数的函数。发现控制器不是持久的,我把参数放回去,现在当我调用方法时它拒绝识别参数。
I'm using this url syntax to call the action:
我正在使用这个 url 语法来调用操作:
http://localhost:2316/Inventory/ViewStockNext/11
Any ideas why I would get this error and what I need to do to fix it?
任何想法为什么我会收到此错误以及我需要做什么来修复它?
I've tried adding another method that takes an integer to the class it it also fails with the same reason. I've tried adding one that takes a string, and the string is set to null. I've tried adding one without parameters and that works fine, but of course it won't suit my needs.
我尝试添加另一个方法,该方法将一个整数添加到类中,但由于相同的原因它也失败了。我尝试添加一个带字符串的字符串,并且该字符串设置为 null。我试过添加一个没有参数的,效果很好,但当然它不适合我的需要。
采纳答案by Jarrett Meyer
Your routing needs to be set up along the lines of {controller}/{action}/{firstItem}
. If you left the routing as the default {controller}/{action}/{id}
in your global.asax.cs
file, then you will need to pass in id
.
您的路由需要按照{controller}/{action}/{firstItem}
. 如果您{controller}/{action}/{id}
在global.asax.cs
文件中将路由保留为默认值,则需要传入id
.
routes.MapRoute(
"Inventory",
"Inventory/{action}/{firstItem}",
new { controller = "Inventory", action = "ListAll", firstItem = "" }
);
... or something close to that.
......或类似的东西。
回答by Matt Mitchell
To rephrase Jarret Meyer's answer, you need to change the parameter name to 'id' or add a route like this:
要改写Jarret Meyer 的回答,您需要将参数名称更改为 'id' 或添加这样的路由:
routes.MapRoute(
"ViewStockNext", // Route name
"Inventory/ViewStockNext/{firstItem}", // URL with parameters
new { controller = "Inventory", action = "ViewStockNext" } // Parameter defaults
);
The reason is the default route only looks for actions with no parameter or a parameter called 'id'.
原因是默认路由只查找没有参数或名为“id”的参数的操作。
Edit: Heh, nevermind Jarret added a route example after posting.
编辑:嘿,没关系 Jarret 在发布后添加了一个路线示例。
回答by RAL
Or, you could try changing the parameter type to string, then convert the string to an integer in the method. I am new to MVC, but I believe you need nullable objects in your parameter list, how else will the controller indicate that no such parameter was provided? So...
或者,您可以尝试将参数类型更改为字符串,然后在方法中将字符串转换为整数。我是 MVC 的新手,但我相信您的参数列表中需要可空对象,否则控制器将如何指示未提供此类参数?所以...
public ActionResult ViewNextItem(string id)...
回答by Oskar Duveborn
public ActionResult ViewNextItem(int? id)
makes the id
integer a nullable type, no need for string<->int conversions.
public ActionResult ViewNextItem(int? id)
使id
整数成为可空类型,不需要 string<->int 转换。
回答by Felix
There is another way to accomplish that (described in more details in Stephen Walther's Pager example
还有另一种方法可以做到这一点(在 Stephen Walther 的Pager 示例中有更详细的描述
Essentially, you create a link in the view:
本质上,您在视图中创建一个链接:
Html.ActionLink("Next page", "Index", routeData)
In routeData you can specify name/value pairs (e.g., routeData["page"] = 5), and in the controller Index function corresponding parameters receive the value. That is,
在 routeData 中,您可以指定名称/值对(例如,routeData["page"] = 5),并且在控制器 Index 函数中对应的参数接收该值。那是,
public ViewResult Index(int? page)
will have pagepassed as 5. I have to admit, it's quite unusual that string ("page") automagically becomes a variable - but that's how MVC works in other languages as well...
将已页面为5。我不得不承认过去了,这是相当不寻常的字符串(“页”)自动地成为一个变量-但那是MVC在其他语言中是如何工作的,以及...
回答by Bart Calixto
you can change firstItem to id and it will work
您可以将 firstItem 更改为 id 它将起作用
you can change the routing on global.asax (i do not recommed that)
您可以更改 global.asax 上的路由(我不建议这样做)
and, can't believe no one mentioned this, you can call :
而且,不敢相信没有人提到这一点,您可以致电:
http://localhost:2316/Inventory/ViewStockNext?firstItem=11
In a @Url.Action would be :
在@Url.Action 中将是:
@Url.Action("ViewStockNext", "Inventory", new {firstItem=11});
depending on the type of what you are doing, the last will be more suitable. Also you should consider not doing ViewStockNext action and instead a ViewStock action with index. (my 2cents)
根据你正在做的事情的类型,最后一个会更合适。此外,您应该考虑不执行 ViewStockNext 操作,而是执行带有索引的 ViewStock 操作。(我的 2 美分)
回答by Aristoteles
The reason for the special treatment of "id" is that it is added to the default route mapping. To change this, go to Global.asax.cs, and you will find the following line:
对“id”进行特殊处理的原因是它被添加到默认路由映射中。要更改此设置,请转到 Global.asax.cs,您将找到以下行:
routes.MapRoute ("Default", "{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" });
Change it to:
将其更改为:
routes.MapRoute ("Default", "{controller}/{action}",
new { controller = "Home", action = "Index" });
回答by Matthew Nichols
Headspring created a nice library that allows you to add aliases to your parameters in attributes on the action. This looks like this:
Headspring 创建了一个不错的库,允许您在操作的属性中为参数添加别名。这看起来像这样:
[ParameterAlias("firstItem", "id", Order = 3)]
public ActionResult ViewStockNext(int firstItem)
{
// Do some stuff
}
With this you don't have to alter your routing just to handle a different parameter name. The library also supports applying it multiple times so you can map several parameter spellings (handy when refactoring without breaking your public interface).
有了这个,你不必为了处理不同的参数名称而改变你的路由。该库还支持多次应用它,因此您可以映射多个参数拼写(在不破坏公共接口的情况下重构时很方便)。
You can get it from Nugetand read Jeffrey Palermo's article on it here
回答by Yar
or do it with Route Attribute:
或者使用 Route 属性来实现:
public class InventoryController : Controller
{
[Route("whatever/{firstItem}")]
public ActionResult ViewStockNext(int firstItem)
{
int yourNewVariable = firstItem;
// ...
}
}
回答by Sasha Yakobchuk
Using the ASP.NET Core Tag Helper feature:
使用 ASP.NET Core 标签助手功能:
<a asp-controller="Home" asp-action="SetLanguage" asp-route-yourparam1="@item.Value">@item.Text</a>