3

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

2 Answers 2

8

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.

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

Comments

4

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

2 Comments

Can you post the complete code? For example, you're missing the inclusion of jquery in order for the $ to work, and how are you calling the writeLog function in the cshtml?
After struggling a lot, this answer nearly solved my problems, Thanks a lot @Jason

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.