4

I have an html link in one file

<a href="#" onClick="xupdate('Home')" id="padlink">Home</a>

On click I want a js function(in another file, with extension js) to execute and that is:

function xupdate(string) {
     document.title = string;
     //Call razor c# function
}

Now I have a c# function(it reads files and displays their information) in a cshtml file:

@helper fileRead(String file) {
            var dataFile = Server.MapPath(file);
            Array userData = File.ReadAllLines(dataFile);
            foreach (string dataLine in userData) {
                foreach (string dataItem in dataLine.Split(',')) {
                    //dataItem <text>&nbsp;</text>
                    @Html.Raw(dataItem);
                 }
             }
}

I want to call the fileRead function from the js xupdate() function and send the value of string into fileRead as a parameter.Is there a way to do this?

Note: I have already included the html link in the cshtml file and my functions work perfectly. Also I know that I have to include a file extension when calling the c# function.

3 Answers 3

2

You can not call C# function from javascript directly, Because javascript execute on client side and C# function execute at server side.

So you must call it other way like AJAX.

Define your function in controller and call it via AJAX call.

Sign up to request clarification or add additional context in comments.

1 Comment

This is no longer correct. Please see learn.microsoft.com/en-us/aspnet/core/blazor/…
1

Use AJAX:

var ret = null;
$.ajax({
   async: false,
   url: "YourFunctionName_in_Controller",
   dataType: "json",
   success: function (data) {ret = data;}
      });
return ret;

Comments

0
DotNet.invokeMethodAsync('{ASSEMBLY NAME}', '{.NET METHOD ID}', {ARGUMENTS});

https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/call-dotnet-from-javascript?view=aspnetcore-6.0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.