ASP.NET MVC F # controller actions ignoring parameter
I have a C # ASP.NET MVC project, but my controllers are written in F #.
For some reason, the following code doesn't work as expected:
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 action parameter appears to be ignored ...
Results in this error message:
The parameter 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. The optional parameter must be a reference type, type null, or be declared as an optional parameter.
Parameter name: parameters
Otherwise, the controller works fine. I know a lot of people have written F # MVC code, so any ideas where I'm going wrong?
a source to share
The problem is that the name of the controller parameter must match the name given in the mapping, which indicates how to translate the url to the controller call.
If you look at the file Global.asax.cs
(which you can also translate to F #), you will see something like this:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index",
id = UrlParameter.Optional } // Parameter defaults
);
The name id
indicates the expected name of the parameter, so you need to adjust your F # code to accept a parameter named id
like this:
member x.Index(id:int) =
x.ViewData.["Message"] <- sprintf "got %d" id
x.View() :> ActionResult
You can use a type Nullable<int>
if you want to make the parameter optional.
For a programmer using the static type safety provided by F #, it is somewhat surprising that ASP.NET MVC relies on so many dynamic tests that it is not checked at compile time. Hope one day there will be an even nicer web framework for F # :-).
a source to share