Ginterhauser
Ginterhauser

Reputation: 196

C# function calling in cshtml

I am not able to call a function in my CSHTML code, despite many efforts. Is a construction like this even roughly possible to work?

***Function***
@functions {
    public void deleteRecord(int id, Database db)
    {
        db.Execute("DROP INDEX "+id+"ON Students");
    }
}

***Button calling that function***
<td><button onclick="@deleteRecord(row.No, db)">Delete</button></td>

db is declared earlier SQL database

Upvotes: 0

Views: 14476

Answers (2)

Fka
Fka

Reputation: 6234

This is really, really bad approach. Firstly, you are breaking MVC rules which are strict - model for data, view for presenting data and controller for ensuring interaction between model and view layer.

Secondly, you are trying to query database via raw SQL queries. It is not as bad as first problem, but did you consider using ORM like Entity Framework or NHibernate.

In your case, I propose you to use piece of JavaScript and C# to reach your target.

It should looks more or less like this:

File view.cshtml

<td><button id="deleteButton">Delete</button></td>

File script.js

$("#deleteButton").click(function() {
    $.get("/SomePage/Delete/12")
    .done(function(obj) {
        // display result or whatever you want
    });
})

File SomePageController.cs

public ActionResult Delete(int id)
{
    // delete object from database
}

Upvotes: 1

David
David

Reputation: 218808

Is a construction like this even roughly possible to work?

If it is, it really shouldn't be. This is mixing concerns in a very bad (difficult to debug/support) way.

Your server-side code should be in your server-side objects, not in your client-side views. If this is MVC, that method probably belongs on a model. If this is WebForms, that method probably still belongs on a model or possibly in code-behind.

Don't put methods in your view. You probably can't anyway, since a view isn't a class and methods need to be in classes. But even if you find some hack to allow you to do this, don't.

Edit: I also just noticed that you're trying to invoke this method from a client-side action. Even if you get this to compile, this won't work. Client-side code can't directly call methods in server-side code, and vice-versa. Think of a web application as actually being two applications, one running on the server and one running in the browser. They can communicate with each other, but they're different languages running on different platforms on entirely different computers, they can't see each other's code.

Upvotes: 0

Related Questions