What I’m trying to do is to call function by a button.
i'll leave you with a simple code that doesn't work!:
@{
protected void print()
{
@<p>WELCOME!</p>
}
}
<form>
<button onclick="print" value="CLICK ME"/>
</form>
any idea on how to accomplish what im trying to do in the code above?
NOTE: IM NOT USING MVC
You can't do it like this.It is not ASP.NET WebForms
.
So if you want to Execute a C# function on Button click in Razor, you must could create a Controller
,then when user clicks a button you must can call a javascript function and it sends an ajax request to your controller then get the data (if there is data) and display it.
Update: Here is an alternative simple sample about how to do this:
In your Controller Add this Method:
public ActionResult GetMessage()
{
string message = "Welcome";
return new JsonResult {Data = message,JsonRequestBehavior = JsonRequestBehavior.AllowGet};
}
And in your View (HTML):
<input type="button" onclick="GetMessage()" value="Get Message"/>
<p></p>
JavaScript:
function GetMessage() {
$.get("/Home/GetMessage", function (data) {
$("p").html(data);
});
}
And don't forget to import jQuery library:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
PS: I assume your Controller name is HomeController, you must change the url if it has different name:
$.get("/{Controller-Name}/{Action-Name}", ...)