Search code examples
c#asp.net-corerazor-pages

Call C# function on cshtml file


I've started learning asp.net these days and i'm trying to call a C# function on cshtml file.

ToDoList.cshtml:

function submitClick() {
  const checkbox = document.getElementById("checkbox").checked;
  const title = document.getElementById("taskTitle").textContent;

  @Model.newTaskChecked = checkbox.checked;
  @Model.newTaskTitle = title.textContent;
  @Model.addTask();
}

ToDoList.cshtml.cs:

public void addTask()
{
  tasks.Add(this.newTaskTitle, this.newTaskChecked);
}

The compiler is saying that Não é possível converter implicitamente tipo "void" em "object". What do i have to do to make it work?


Solution

  • First, please forget cshtml.cs and things like that. This is Razor MVC, so you will have a cshtml with mixed html and c#

    From the c# you can use any c# in your project, when it is declared public.

    Suppose you have some Class1.cs (in your project) containing a method function MyTask that looks like this..

    namespace MyNamespace
    {
       public class Class1
       {
          public static bool MyTask(int x)
          { return x == 0; }
        }
    }
    

    .. then in your.cshtml you can put a using MyNamespace, OR you can refer to MyTask with its full name. Maybe that is easier to explain. You could use it to test and put something in the HTML, like:

     @if (MyNamespace.Class1.MyTask(1))
     {
       <b>ok</b>
     } 
     else
     {
       <b>nono need 0</b>
     }
    

    This will say "nono need 0" in the browser.

    EDIT: you can't expect to let this function work as intended:

     function submitClick() {
       const checkbox = document.getElementById("checkbox").checked;
       const title = document.getElementById("taskTitle").textContent;
    
       @Model.newTaskChecked = checkbox.checked;
       @Model.newTaskTitle = title.textContent;
       @Model.addTask();
     }
    

    Here you try to assign things to your model directly, from Javascript. The checkbox.checked is unknown at the server side. The c# runs ONLY on the server side.. so to get your checkbox and textcontent to the server, you will have to put a submit button and POST your form. And if you do that, you probably won't need to call c# from anywhere in your cshtml !