Matt
Matt

Reputation: 2088

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

Upvotes: 3

Views: 9702

Answers (2)

Mike Brind
Mike Brind

Reputation: 30035

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.

Upvotes: 8

Jason Pan
Jason Pan

Reputation: 21848

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

Upvotes: 4

Related Questions