我对使用WebSharper很陌生,并且我可能以错误的方式进行操作。
我的目标是通过更新代表要更新页面的一部分的Var<Doc>
变量来更新用户页面的内容。我很高兴知道我是否可以从服务器端代码更新Var<Doc>
并将其反映在用户的浏览器中。
下面是一个简单的示例:
let TestPage ctx =
let clientPart = Var.Create <| Doc.Empty
clientPart .Value <- div [] [ text "This content is dynamically inserted" ]
Templating.Main ctx EndPoint.Home "Home" [
h1 [] [text "Below is a dynamically inserted content:"]
div [] [ client <@ clientPart .View |> Doc.EmbedView @> ]
]
我收到的错误是:
System.Exception:RPC JSON转换期间发生错误---> System.Exception:无法在WebSharper.UI.Elt类型中查找翻译的字段名称以进行写入',其字段为:docNode,elt,rvUpdates,更新
有关Views的WebSharper 4文档还指出:
仅当使用 这些方法之一 :
将结果视图包含在文档中时运行
- Doc.BindView
- Doc.EmbedView
- textView
等
如果我尝试这样做,则会产生类似的错误:
type SomeTemplate = Template<"SomeTemplate.html">
clientDoc.Value <- SomeTemplate().Doc()
在上面的代码中,Templating.Main
与默认的WebSharper项目相同:
module Templating =
...
let Main ctx action (title: string) (body: Doc list) =
let t = MainTemplate().Title(title).MenuBar(MenuBar ctx action).With("Body", body)
let doc : Doc = t.Doc()
doc |> Content.Page
答案 0 :(得分:1)
以下是在服务器端调用RPC并将其存储到客户端Var<>
中的示例:
module ServerFunctions =
let mutable ServerState = ("Zero", 0)
let [< Rpc >] addToState n = async {
let state, counter = ServerState
let newCounter = counter + n
let newState = if newCounter = 0 then "Zero" else "NonZero"
ServerState <- newState, newCounter
return newState
}
[< JavaScript >]
module ClientFunctions =
open WebSharper
open WebSharper.UI
open WebSharper.UI.Html
open ServerFunctions
let zeroState = Var.Create "do not know"
let clientDoc() =
div [] [
h1 [] [ text "State of zero on server:" ]
h2 [] [ text zeroState.V ]
Doc.Button "increment" [] (fun () -> async { let! state = addToState 1
zeroState.Set state
} |> Async.Start)
Doc.Button "decrement" [] (fun () -> async { let! state = addToState -1
zeroState.Set state
} |> Async.Start)
]
module Server =
open global.Owin
open Microsoft.Owin.Hosting
open Microsoft.Owin.StaticFiles
open Microsoft.Owin.FileSystems
open WebSharper.Owin
open WebSharper.UI.Server
open WebSharper.UI.Html
type EndPointServer =
| [< EndPoint "/" >] Hello
| About
let url = "http://localhost:9006/"
let rootdir = @"..\website"
let site() = WebSharper.Application.MultiPage(fun context (s:EndPointServer) ->
printfn "Serving page: %A" s
Content.Page(
Title= ( sprintf "Test %A" s)
, Body = [ h1 [] [ text <| sprintf "%A" s ]
Html.client <@ ClientFunctions.clientDoc() @> ])
)