Calling a C# function by a HTML button
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}", ...)
Call a C# function using HTML onclick button
You can call one method where you check role and redirect on another action or just call a private method.
public ActionResult OnGet()
{
if (NTUser.Role != Role.Admin)
{
return RedirectToPage("/Denied");
}
else
{
return RedirectToAction(Matching);
}
...other if with return
}
public ActionResult Matching()
{
//dosomething
}
view
if you need post then use it
@using (Html.BeginForm("OnGet", "YourControllerName", FormMethod.Post))
{
<button type="submit" id="cmdAction" runat="server">
Match and Show the result
</button>
}
if you need just get
@Html.ActionLink("Match and Show the result", "OnGet", "YourControllerName") //without params
dont forget add attribute [HttpPost]
or [HttpGet]
(get just for better readability code)
Call C# function from html button
After trying for some time, I still coudn't get the function to be called (I tried the above suggestions). So I solved it as following: I made a Session with all the products of my cart and redirected to a separate page. On this page I made a datalist and wrote a SelectCommand to select all the items in the session
Razor Page onclick button, call method
If you want to call backend handler with button,you need to put the button into a form,and try to change the format of the handler name.
The default convention works by matching the HTTP verb used for the request to the name of the method, which is prefixed with "On": OnGet(), OnPost(), OnPut() etc.And after OnGet(), OnPost(), OnPut(),etc
,the first letter needs to be
a capital letter.Here is a demo:
cshtml:
<form method="post" asp-page-handler="FuncaoClique">
<button>OnClickTest</button>
</form>
cshtml.cs:
public void OnPostFuncaoClique()
{
Console.WriteLine("Hello");
}
call c# function from javascript onclick event button
To trigger button event, you have to add this line of code in javascript.
document.getElementById("btn_newpl").click();
Your button must have runat="server"
and OnServerClick="btn_newpl_Click"
attributes.
If your problem is that the input
element is in javascript string, than you can extract the string value of input
and concatenate to your string on client side.
<input type="button" id="btn_newpl" value="submit"
OnServerClick="btn_newpl_Click"
runat="server" />
<script>
var tmp = document.createElement("div");
tmp.appendChild(document.getElementById('btn_newpl'));
google.maps.event.addListener(marker, "click", function (e) {
var infoWindow = new google.maps.InfoWindow({
content:
'<div><input type="text" id="txt_newpl" value="place name"/>' +
'</br>'+tmp.innerHTML+'</div>'
})
});
</script>
Please note that you don't actually call a C# function, you just trigger the click event on webforms and a postback to sever will be done. The server will figure out which event has been triggered and will execute the C# function.
Source: How to call a code behinds button click event using javascript
Blazor execute C# and JS function in one button onclick event
Inject the JSRuntime:
@inject IJSRuntime JsRuntime
Bind the onclick event of the button:
<button @onclick=ButtonClicked>Test</button>
and execute the JavaScript function:
private async Task ButtonClicked()
{
Console.WriteLine("From C#");
await JsRuntime.InvokeVoidAsync("console.log", "From js");
}
When invoking JS-functions, pass the function name as first argument followed by all parameters
Related Topics
C#: Throwing Custom Exception Best Practices
Finding the Concrete Type Behind an Interface Instance
Regex to Get Src Value from an Img Tag
Convert Utc Datetime to Another Time Zone
How to Lock/Unlock a File Across Process
ASP.NET Core MVC - Client-Side Validation for Custom Attribute
Entity Framework the Underlying Provider Failed on Open
Auto Create Database Tables from Objects, Entity Framework
How Are Dlls Loaded by the Clr
Instantiate a Class from Its Textual Name
How to Add Text to a Wpf Label in Code