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***
Deletedb is declared earlier SQL database
Talk1:
No, the code you put in an onclick handler has to be JavaScript. You can't magically allow a button in your page to call a function on your server by putting it in your razor file.
Talk2:
No. You're confusing serverside/clientside and you're destroying the MVC pattern here. But firing of a service call is easy.
Solutions1
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
DeleteFile 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
}
Solutions2Is 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.