Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Controller with optional parameter in F#

I create controller with optional parameter accordingly:

type ProductController(repository : IProductRepository) =
inherit Controller()
member this.List (?page1 : int) = 
    let page = defaultArg page1 1

When I have started application it gives me error: "System.MissingMethodException: No parameterless constructor defined for this object."

I know this error from dependency injection, here is my Ninject settings:

static let RegisterServices(kernel: IKernel) =
    System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver <- new NinjectResolver(kernel)

    let instance = Mock<IProductRepository>()
                    .Setup(fun m -> <@ m.Products @>)
                    .Returns([
                                new Product(1, "Football", "", 25M, "");
                                new Product(2, "Surf board", "", 179M, "");
                                new Product(3, "Running shoes", "", 95M, "")
                    ]).Create()

    kernel.Bind<IProductRepository>().ToConstant(instance) |> ignore

    do()

The issue is when I remove my optional parameter from controller all is working fine. When change parameter for regular one it give me following error: The parameters dictionary contains a null entry for parameter 'page' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ViewResult List(Int32)' in 'FSharpStore.WebUI.ProductController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters

This is my routes settings:

static member RegisterRoutes(routes:RouteCollection) =
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}")


    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        { controller = "Product"; action = "List"; id = UrlParameter.Optional } // Parameter defaults
    ) |> ignore

Have anyone done optional parameter for controller? I'm working on pilot project for my colleague to promote F# to our stack. Thanks

like image 855
Martin Bodocky Avatar asked Nov 27 '25 04:11

Martin Bodocky


1 Answers

Another F# - C# interop pain :P

The F# optional parameter is a valid optional parameter for F# callers, however in C# this parameters will be FsharpOption<T> objects.

In your case you must use a Nullable<T>. So, the code looks like:

open System.Web.Mvc
open System
[<HandleError>]
type HomeController() =
    inherit Controller()    
    member this.Hello(code:Nullable<int>) =        
        this.View() :> ActionResult

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!