Home > Software design >  Call Model function from javascript in razor page
Call Model function from javascript in razor page

Time:04-01

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>
}

CodePudding user response:

I agree with enter image description here

enter image description here

CodePudding user response:

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.

  • Related