[英]ASP.NET MVC F# controller action ignoring parameter
I have a C# ASP.NET MVC project but my controllers are written in F#. 我有一个C#ASP.NET MVC项目,但是我的控制器是用F#编写的。
For some reason, the following code doesn't work properly: 由于某些原因,以下代码无法正常工作:
namespace MvcApplication8.Controllers
open System.Web.Mvc
[<HandleError>]
type ImageController() =
inherit Controller()
member x.Index (i : int) : ActionResult =
x.Response.Write i
x.View() :> ActionResult
The parameter of the action is seemingly ignored... 动作的参数似乎被忽略了...
http://localhost:56631/Image/Index/1 HTTP://本地主机:56631 /图像/索引/ 1
Results in this error message: 结果出现此错误信息:
The parameters dictionary contains a null entry for parameter 'i' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Index(Int32)' in 'MvcApplication8.Controllers.ImageController'. 参数字典包含用于'MvcApplication8.Controllers.ImageController'中方法'System.Web.Mvc.ActionResult Index(Int32)'的非空类型'System.Int32'的参数'i的空条目。 An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. 可选参数必须是引用类型,可为空的类型,或者必须声明为可选参数。
Parameter name: parameters
The controller otherwise works fine. 否则控制器可以正常工作。 I know that plenty of people have written F# MVC code, so any ideas where I'm going wrong? 我知道很多人都编写了F#MVC代码,所以我有什么想法要出错吗?
The problem is that the name of the parameter of the controller needs to match the name specified in the mapping that specifies how to translate the URL to a controller call. 问题在于,控制器参数的名称需要与在映射中指定的名称匹配,该映射指定了如何将URL转换为控制器调用。
If you look into the Global.asax.cs
file (which you should be able to translate to F# too), then you would see something like this: 如果查看Global.asax.cs
文件(您也应该能够将其转换为F#),那么您将看到类似以下内容:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index",
id = UrlParameter.Optional } // Parameter defaults
);
The name id
specifies the expected name of the parameter, so you need to adjust the F# code to take a parameter named id
like this: 名称id
指定参数的预期名称,因此您需要调整F#代码以采用名为id
的参数,如下所示:
member x.Index(id:int) =
x.ViewData.["Message"] <- sprintf "got %d" id
x.View() :> ActionResult
You can use Nullable<int>
type if you want to make the parameter optional. 如果要将参数设为可选,则可以使用Nullable<int>
类型。
For a programmer used to the static type safety provided by F#, it is somewhat surprising that ASP.NET MVC relies on so many dynamic tests that aren't checked at compile-time. 对于习惯于F#提供的静态类型安全性的程序员而言,ASP.NET MVC依赖于如此之多的动态测试,这些动态测试在编译时并未进行检查,这有些令人惊讶。 I would hope that one day, there will be some nicer web framework for F# :-). 我希望有一天,会有一些更好的F#Web框架:-)。
what's your Route look like? 您的路线是什么样的? is it routing to id? 路由到ID吗? in which case rename i to id 在这种情况下,将我重命名为id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.