Search code examples
asp.net-corerazorrazor-pages

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

Solution

  • 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