Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Model function from javascript in razor page

Is it possible to call a Model function in a razor page like this (the function is never hit):

<input id="btnWork" type="submit" value="Work" onclick="writeLog("add to log");" />

However, I have this in my razor page and it hits the function on page load only:

{
<script>
     function writeLog(msg)
     {
         @IndexModel.logHolder.Add("testing 123");
     }
</script>
}
like image 993
Matt Avatar asked Aug 06 '26 06:08

Matt


2 Answers

No, you cannot call a server-side method directly from JavaScript. What you can do is to use JavaScript to make an HTTP request to a page handler method that invokes the server-side method instead. Typically, you would use a named handler method for this

Add a simple named handler to your PageModel that responds to GET requests and takes a string as a parameter. The handler's name is Add i.e. the name of the method without the OnGet, OnPost part:

public void OnGetAdd(string msg)
{
    // processing goes here        
}

Then add the following to your Razor page itself:

<input id="btnWork" type="submit" value="Work" onclick="writeLog('add to log');" />

@section scripts{
    <script>
    function writeLog(msg){
        fetch(`?handler=Add&msg=${msg}`);
    }
    </script> 
}

This uses the Fetch API to make the HTTP request, with the handler specified in the query string along with the msg parameter. When you click the button, you should see the breakpoint on the handler method hit, and the msg parameter is whatever you specified in the onclick event i.e. "add to log" in this example.

like image 87
Mike Brind Avatar answered Aug 09 '26 12:08

Mike Brind


I agree with Mike Brind. At the same time, I also did some testing work, which I also shared.

We can't call C# function from javascript directly, Because javascript execute on client side and C# function execute at server side. So we need to call it other way like AJAX.

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

JS Code:

<script>
   function writeLog(msg) {
      $.ajax({
        url: '?handler=WriteLog&msg='+msg,
        success: function (data) {
            alert(data);
        },
        error: function (error) {
          alert("Error: " + error);
        }
      })
    }
</script>

Model Function Code:

public IActionResult OnGetWriteLog(string msg)
{
    return new JsonResult(msg); 
}

Test Results:

enter image description here

enter image description here

like image 37
Jason Pan Avatar answered Aug 09 '26 12:08

Jason Pan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!