【问题标题】:Websharper, Sitelets and FormsWebshaper、Sitelets 和表单
【发布时间】:2015-04-08 17:23:51
【问题描述】:

我一直在尝试使用 Websharper 创建一个表单来收集用户输入。到目前为止,我已经为我的网站确定了三个操作:

type MyAction =
    | [<CompiledName "">] Index
    | [<Method "POST">] GetUser of username : string
    | Stats of username: string

使用 Sitelet.Infer 我已经设法实现了基本的 UI,但我不知道如何引用我的输入框的内容(用户名输入):

Sitelet.Infer <| function
    | Index ->
        Content.PageContent <| fun ctx ->
            let usernameInput= Input [Text ""]
            { Page.Default with
                Title = Some "Welcome!"
                Body = 
                    [ 
                        Div [
                            Form
                                [
                                    usernameInput-< [Name "username" ]
                                    Input [Value "Request"] -< [Type "submit" ]

                                ] -< [ Attr.Action (ctx.Link (* GetUser usernameInput.Content *) ); Method "POST" ]
                        ]
                    ]
            }
    | GetUser username ->
        Content.Redirect <| Stats username
    | Stats username ->
        Content.PageContent <| fun ctx ->
            { Page.Default with
                Body = [Text ("Stats for " + username)] }

我注意到 usernameInput 没有像“Value”这样的任何字段,我猜它需要强制转换或者我做错了什么。

我不想在我的代码中使用 JavaScript(是否可以在 Sitelet 中混合 Html.Server 和 Html.Client 元素?)。

【问题讨论】:

    标签: html forms f# websharper


    【解决方案1】:

    表单 POST 数据不通过 URL 传递,因此您不能使用 ctx.Link 传递它。它通过请求正文自动传递,格式类似于 GET 查询参数(例如,在您的情况下,username=myusername)。 Sitelet.Infer 目前还没有解析这个,尽管我们将来可能会添加它。现在您可以使用不带参数的操作,然后从请求中提取数据:

    type MyAction =
        | [<Method "POST">] GetUser
        | // ...
    
    Sitelet.Infer <| function
        | GetUser ->
            Content.CustomContentAsync <| fun ctx ->
                match ctx.Request.Post.["username"] with
                | None -> Content.NotFound
                | Some username -> Content.Redirect <| Stats username
                |> Content.ToResponseAsync ctx
        | // ...
    

    【讨论】:

    • 我实现了这个,但是字典 ctx.Request.Post.[] 不包含任何值(即,每次在上面的模式匹配中遇到“无”情况时;我已经对其进行了调试并注意到了ctx.Request.Post 中没有值)。为了使其正常工作,我还需要做些什么吗?
    • 补充一点:我的浏览器显示生成的 POST 请求包含“用户名”值,但不知何故 ctx(在 F# 端)没有。
    • 好的 - 我在这里得到了答案:websharper.com/question/79205/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多