简体   繁体   中英

How to Pass a c# variable to javascript in Blazor Web Assembly

I am using Blazor Web assembly and the 3rd party component does not support @onitnput, @bind-value:event="oninput". To try and get around this I am attempting to use JS to trigger a c# function. (I have other stuff that is triggering the "onchange" on input so when you look at my example just think of it as oninput, and that is working).

Main issue: I need to pass a reference to the page into the method being called by onchange so that I can then call the c# method from JS but I can't get it to pass the parameter. Here is my markup

<RadzenHtmlEditor @bind-Value=@SurveyScriptNode.Script onchange="callCSharpMethodNoParams(@DotNetObjectReference.Create(this))" style="height: 500px; margin-bottom: 1rem; opacity: 1;" UploadUrl="upload/image" Paste=@OnPaste Execute=@OnExecute id="scriptBuilder_surveyScriptNode_ScriptEditor">

I also tried what was suggested Here but could not get it working either

<RadzenHtmlEditor @bind-Value=@SurveyScriptNode.Script onchange="callCSharpMethodNoParams(<%=DotNetObjectReference.Create(this)%>)" style="height: 500px; margin-bottom: 1rem; opacity: 1;" UploadUrl="upload/image" Paste=@OnPaste Execute=@OnExecute id="scriptBuilder_surveyScriptNode_ScriptEditor">

Is there any way to do this in Blazor?

Thank you for your time.

As a workaround I am doing this:

  • Hide a check box

  • Set a js oninput method on the desired control, this will call a js function that sets the hidden check box to true

  • Since the hidden checkbox can't @bind when JS updates the value and it will not update the value when calling StateHasChanged(), you need to implement a timer that uses JS interop to call a js function to return the value of the hidden check box to your c# code.

  • Set the value of the c# variable to the returned value of the previous step

  • Create another method in the c# that uses JS Interop to call the js function you use in your on input, call this method in the setter of the c# variable but make sure to only do it if the page is already initialized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM