Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call razor c# function from javascript function

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.

like image 646
Hzakv Avatar asked Oct 19 '25 18:10

Hzakv


2 Answers

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.

like image 185
Manish Parakhiya Avatar answered Oct 22 '25 08:10

Manish Parakhiya


Use AJAX:

var ret = null;
$.ajax({
   async: false,
   url: "YourFunctionName_in_Controller",
   dataType: "json",
   success: function (data) {ret = data;}
      });
return ret;
like image 34
Omar Yassin Carcelen Avatar answered Oct 22 '25 07:10

Omar Yassin Carcelen