Asp.net Core and Ajax Buttons
Working on an internal web app, and I am not a web guy. Ajax makes my brain hurt. Today we learn how to wire up a button to Ajax and make it do things. Also I’m super bad at blogging and just wanted to put this some where cause I just spent a long time figuring it out.
First, we have to setup our foundation so we know what we’re talking about. Names slightly changed from my internal work code cause I have secrets.
In this case we have a Controller Named “Project”, and an Action in that controller named “Project_Transfer”.
That controller code goes a little something like this:
[HttpPost]
public IActionResult Project_Transfer()
{
/// A bunch of stuff it takes a while to do
}
We have a model that matches this that sets some variables, houses a method it uses and such, but those aren’t important right now. Next up we have to setup our View.
@using (Html.BeginForm(“Project_Transfer”,
“Project”, FormMethod.Post,
new { encType = “multipart/form-data”, id = “myform”, name = “myform” }))
{
<div class=”form-group”> <h5>Enter Patch Number If Applicable, Leave Empty for None:</h5> <input type=”number” name=”patchNumTxt” />
<div class=”col-md-10"> </div> </div> }
<div id=”divProcessing” style=”display:none;”> <figure><img src=”~/images/AnimatedProgressBar.gif”></figure> <p>Transferring, please wait or click Cancel to terminate. . . </p> </div>
This just has a text box we can put a number in that the controller will then grab to do magic processing when the button is clicked.
Now comes the AJAX, or the part that threw me for a loop for like 3 days.Here’s the completed AJAX, then I’ll explain:
Now comes the AJAX, or the part that threw me for a loop for like 3 days.Here’s the completed AJAX, then I’ll explain:
<script src=”https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"></script>
$(function () {
// Attach click handler to the submit button:
$(‘#btn_transfer’).click(function () {
$(‘#divProcessing’).css({ ‘display’: ‘block’ });
$(‘#myform’).submit();
$(“#myform”).on(“btn_transfer”, function (event) {
event.preventDefault();
var url = $(this).attr(“action”);
var formData = $(this).serialize();
$.ajax({
url: url,
type: “POST”,
data: formData,
dataType: “json”,
success: function (resp) {
$(‘#divProcessing’).css({ ‘display’: ‘hide’ });
}
})
});
});
});
So, what we’re doing here is loading the jquery script source first. This is important. In our script block we attach a click handler to the form. When the button on the form is pressed, it will load the action to take place as going to our Project Controller and Project_Transfer Action.
Then it hits this AJAX, and we use some CSS to show our div block containing the Loading gif and text we want to show. Once unhidden, it then moves to a submit action.
We prevent the default action using the JQuery
We prevent the default action using the JQuery
preventDefault() method when the form submit event occurs, otherwise, form submission will proceed automatically, as before, and any code we place in our handler won't work right.
Next we get what we need from our form in order to submit our Ajax request. First, we grab the Url and stow it in a variable by accessing the form’s action attribute using JQuery. The
action attribute essentially pulls a Url which matches the route we specified in the form declaration (action method, controller name).
Next, we serialize the form data ( in this case, our model data) into another variable, again using JQuery.
Once we have collected these things, we can set up our Ajax request by making the property assignments shown. Note that we need to specify the data type as Json, so that when the request returns, JQuery will recognize it as valid Json. Then, we come to the all-important
success property.
Here on success, we hide the loading gif again, and in my model I use ViewData to populate some text to tell the user the results of action.
I have to give a lot of credit to this site for helping me get this together. This was using older asp.net, but it put me on the right track!
Comments
Post a Comment