-3

I am trying to call C# code within Javascript but it is not working. This is my code:

    @{
      ViewBag.Title = "Db Maintenance";
    }

   <script type="text/javascript">
      function beginSubmit() {
         @{
        Console.WriteLine("DELETING.....");
         }
      }

      function cancelConfigForm() {
        closeWindow("configDbMaitenanceWindow");
      }
    </script>

    <div>
      <button class="k-button k-button-icontext" type="submit" title="Delete Error Records" onclick="beginSubmit()">
        <img src="@Url.Content("~/Content/Icons/metro-submit.png")" class="k-icon blank-background" alt="Submit Icon" />Delete Error Records
      </button>
      <button class="k-button k-button-icontext" type="reset" title="Close the window" onclick="cancelConfigForm()">
        <img src="@Url.Content("~/Content/Icons/metro-cancel.png")" class="k-icon blank-background" alt="Cancel Icon" />Cancel
      </button>
    </div>

"Console.WriteLine" is not even being called. How can I go about callling the C# code on button click?

EDIT I tried

  <text>
         Console.WriteLine("DELETING.....");
  </text>

and it didn't work.

1 Answers1

1

You are mixing 2 completely different technologies.

Razor renders server-side

So your function would be just

function beginSubmit() {

}
//notice empty line, cuz Console.WriteLine("DELETING....."); doesn't return anything

Because c# Console.WriteLine("DELETING....."); doesn't return anything, it just logs DELETING..... when razor engine compiles cshtml file.

JavaScript renders client-side

So you are asking browser to do something for you, call alert, console.log(this is different from c# log) something, or any other thing that browsers allows you to do, not your server.

And you cannot call server-side code from javascript, unless you have (REST)API for that call. Even in this case, you need ajax for calling it from client

Medet Tleukabiluly
  • 11,662
  • 3
  • 34
  • 69
  • How then can I call C# code on button click and put the C# code within the same page? –  Dec 11 '15 at 13:04
  • @Munashe you cannot call server method within javascript, the only solutions is: you make logic on the client, or you make REST call to your server (with ajax) and pass params to server, so that it can handle your logic – Medet Tleukabiluly Dec 11 '15 at 13:07