I want to use the button to run a c# method how to do that? Now if i make a button with
<button type="button" onclick="#class.method()" >execute method</button>
it just executes that method on page load but doesnt do that on button click.
This can be done using standard form or ajax form.
Option 1 - Standard form:
add asp-page-handler attribute to the button and specify the relevant method name, and on the back end create the relevant method with OnPost prefix.
<form method="post">
<button type="button" asp-page-handler="RunMethod">execute method</button>
</form>
Backend method:
public IActionResult OnPostRunMethod()
{
//do whatever...
}
Option 2 - ajax form:
Use data-ajax-url="?handler=RunMethod" directly inside the form attributes or you can use a script to assign the relevant method handler to the form, with this approach you can use multiple buttons inside the same ajax form:
<form method="post" id="myForm"
data-ajax="true"
data-ajax-method="post"
data-ajax-loading="#loading"
data-ajax-failure="failed"
data-ajax-update="#updateMsg">
<button type="submit" id="RunMethod">execute method</button>
</form>
#section Scripts{
<partial name="_ValidationScriptsPartial" />
<script src="~/lib/jquery-ajax-unobtrusive/dist/jquery.unobtrusive-ajax.min.js"></script>
<script>
failed = function (xhr) {
alert('Status: {xhr.status}, Status text: {xhr.statusText}');
}
$("#RunMethod").on("click", function () {
$("#myForm").attr("data-ajax-url", "?handler=RunMethod");
});
});
</script>
}
Backend method:
public IActionResult OnPostRunMethod()
{
//do whatever...
}
see samples here
You need to create a handler method in the Razor page and use asp-page-handler attribute. See here for more information.
Related
I am trying to use Select2.js within my MVC 6 (Core) project, where if a user selects a value (or multiple values) within the first listbox, then they are then provided with an updated list of values within the second listbox. So for example... if a user selects "Ford" and "Renault" from the Manufacturer listbox, then they are only provided with relevant values in the Brand listbox e.g. Mondeo, Mustang, Clio, Megane etc.
My View syntax is:
#model MyProject.ViewModels.MyViewModel
<script type="text/javascript">
$(document).ready(function () {
$('#ManufacturerID').select2({
placeholder: 'Please make a selection...',
width: 500
});
$('#BrandID').select2({
placeholder: 'Please make a selection...',
width: 500
});
});
</script>
<form asp-action="Generation">
<div class="form-horizontal">
<div class="col-md-10">
#Html.ListBoxFor(model => model.ManufacturerID, Model.ManufacturerNames)
#Html.ListBoxFor(model => model.BrandID, Model.BrandNames)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Submit" class="btn btn-default" />
</div>
</div>
</form>
If I click the submit button, the post action method successfully acquires a list of Manufacturer ID's:
// POST: MyController/Generation
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Generation(MyViewModel myViewModel, IEnumerable<int> manufacturerID)
{
return RedirectToAction("Generation");
}
But what I really want is something similar to AJAX Update Panel in Web Forms where the call to the controllers post action method is performed immediately on selecting an option from the listbox, not when the user clicks submit.
Your help is greatly appreciated.
Regards,
X22
$(document).ready(function(){
pageInit();
});
function pageInit(){
$('#ManufacturerNames').off();
$('#ManufacturerNames').on('change', function(e){
//ajax request here
//call pageInit() in your callback to reattach select2
//and event handler if you are fully replacing the dropdown.
});
$('#BrandNames').off();
$('#BrandNames').on('change', function(e){
//ajax request here
//same as callback above depending on how you go about doing this.
});
}
This is the manual way but since you are using a library like select2, they may provide an easy way to set this up in your initialization.
I am new on mvc programming. I have two labels, two textboxes and one button and I have to use devexpress tools. It is like login form. I want to call an actionresult from a controller class when I click the button. How can I do that if it is possible?
That's my button
<dx:ASPxButton ID="ASPxButton1" runat="server" Text="Giriş" OnClick="ASPxButton1_Click" Theme="Moderno" EnableTheming="True"></dx:ASPxButton>
and that's my button click event
<script runat="server">
protected void ASPxButton1_Click(object sender, EventArgs e)
{
}
</script>
and these are in Index.aspx page.
I'm not entirely sure what your asking, but I'll attempt to clarify.
// Model View Controller:
<form action="/Home/Validate" method="post">
<input type="text" name="username" required />
<input type="text" name="password" required />
<input type="submit" value="Submit" />
</form>
That would be in your code, then you hit the button which will submit your form and point to your Validate Controller. Which would look like:
public ActionResult Validate(string username, string password)
{
// Do Stuff, then call your next view and pass model.
return RedirectToAction("Account");
}
Important: In Model View Controller you don't call button clicks, you call Controllers. So you would point your destination to a Controller method (example):
Validate
<input type="button" onclick="/Home/Validate" />
Home - will reference the Controller
Validate - will reference the method within the Controller.
Your code is from the realm of an Web-Forms, if it is all server side code without custom JavaScript then you may be able to simply do:
<asp:UpdatePanel id="updAccount" runat="server">
<ContentTemplate>
// Your button, textbox for Submit (Alleviates Postback).
</ContentTemplate>
</asp:UpdatePanel>
That would be the simpler of the two Web-Forms approach. However, you could indeed use jQuery or JavaScript to accomplish this as well.
I have this snippet of code;
<form action="#Url.Action("Index", "MyController")" method="post" >
<button class="btn btn-large btn-primary" id="btnNext">Click Here</button>
</form>
But when the button is clicked it redirects to http://<domain>:2024/MyController and I get a http error
405.0 Directory listing is not allowed.
If I manually change the url to http://<domain>:2024/MyController/Index I get my page.
When I change the form code to the below it works.
<form action="#Url.Action("MyAction", "MyController")" method="post" >
...
index method declaration is;
public async Task<ActionResult> Index()
{
...
}
So it's an inconvenience, and this is the only place it happens. I can work round it by not using the Index action, but how can I track this down and fix it?
In addition to checking your routing rules, you can use the Html.BeginForm helper method to create forms properly.
#using(Html.BeginForm("Action", "ControllerName"), HttpMethod.Post)
{
//form controls
}
I am trying to do this one http://jquerywall.com/demo-multi-transfer-jquery-ui-selectable/
But the problem is that this multiselect plugin has some buttons.When i click any of these buttons my page gets posted and goes to its methods.
Here are my buttons
<div id="transfer-buttons">
<button id="add-button">Add →</button>
<button id="add-all-button">Add All *→</button>
<button id="remove-button">← Remove</button>
<button id="remove-all-button">←* Remove All</button>
</div>
here are my buttons functions
<script type="text/javascript">
$(function () {
$("#add-button").click(add);
$("#add-all-button").click(addAll);
$("#remove-button").click(remove);
$("#remove-all-button").click(removeAll);
$("#source-list, #target-list").selectable();
addHiglightPlugin();
});
what should i do?
Try adding a type="button" attribute to your buttons. When <button> has no type specified it acts like a submit button.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button
The other thing you can do is prevent default action in your event handlers:
function add(e){
e.preventDefault();
// your code here
}
I have a loop that creates some buttons and (is meant to) make a function call when that button is pressed.
foreach (Answer a in qanswers)
{
//Guid answerid = new Guid();
<form method="post" action="">
<div class="float-left">
<input type="submit" value="#a.Answer1" class="submit" style="width:600px" onmousedown="#{saveTest(a, module, user, quest, healthsafety);}">
<br /><br />
</div>
</form>
}
However, it calls the "saveTest" procedure at page load for each button produced, rather than onmousedown/onmouseclick.
Is it possible to change this?
I assume from this that saveTest is a server side function that you are trying to call.
onmousedown is a client side event and can only directly run client side script.
If you wish to call a server side function then you will need to specify an action in the form that the page will post pack to.
Have a look here for more on this
http://msdn.microsoft.com/en-us/library/system.web.mvc.html.formextensions.beginform(v=vs.108).aspx
A quickly modified version of your code would be:
foreach (Answer a in qanswers)
{
using (Html.BeginForm("saveTest", "ControllerName"))
{
<div class="float-left">
<input type="submit" value="#a.Answer1" class="submit" style="width:600px")>
<br /><br />
</div>
}
}
The button will submit to the controller and action that has specified in the form. So please check carefully which controller and action you have specified.
using (Html.BeginForm("saveTest", "Controller"))
{
}
This is the way you have to specify your form.
Regards,
Pavan.G