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> </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.
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.
Use AJAX:
var ret = null;
$.ajax({
async: false,
url: "YourFunctionName_in_Controller",
dataType: "json",
success: function (data) {ret = data;}
});
return ret;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With