简体   繁体   中英

Run Controller Method when Button is clicked MVC4 C#

I am making a simple application using visual studio 2013, MVC4 and C#. This web app has a table with multiple checkboxes and an Update button disbaled by default. When one or more checkboxes are clicked I activate the button.

The idea here, is to send all the information of the checkboxes (which ones are on or off) to the server when the UPdate button is clicked and then to save those changes in the DB.

To achieve this I am trying to use ajax via jquery, but unfortunatly I am not succeding, because when I click the button nothing happens.

This is the cshtml file that I use to generate the view for the client:

<input type="submit" value="Save Checkbox Changes" class="btn btn-primary disabled" id="SaveCheckboxChanges" />

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.RequiresSetup)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Disabled)
        </th>
    </tr>

    @{
        foreach (var item in Model)
        {

            <tr>
                <td>
                    @Html.EditorFor(modelItem => item.RequiresSetup)
                </td>
                <td>
                    @Html.EditorFor(modelItem => item.Disabled)
                </td>
            </tr>
        }
}
</table>

The javascript code that I have for the button SaveCheckboxChanges is the following:

$("#SaveCheckboxChanges").click(function (event) {
        if (!$("#SaveCheckboxChanges").hasClass("disabled")) {

            $.ajax({
                url: '/Material/UpdateCheckBoxes',
                type: 'POST',
                data: {bla: "bdsjdnjsdnsnd"

                },
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    alert(data.success);
                },
                error: function () {
                    alert("error");
                }
            });
        }

    });

And in my materials controller, I have the following:

[HttpPost]
public ActionResult UpdateCheckBoxes(string bla)
{
    return Content("Working!" +  bla);
}

What I expect, is that after clicking the button, the page shows the "Working" string, meaning that the function in the controller was executed correctly.

However, this is not happening, and all I see is the javascript alert saying "error".

How can I make this ajax request work? What am I missing?

Your controller method returns nothing...

Convert it to the following ::

public String Material()
{
    return "Working!";
}

That's not how things work. When you call Response.Write in response to an AJAX request, then the actual AJAX response is the string "Working!". Nothing will ever be written to the page, unless you take that string and add it to the DOM somewhere yourself.

I've seen 3 incorrect things in your code.

1) [ValidateAntiForgeryToken] You don't implement it in your ajax call, so you should remove it in your controller. (I don't know how to use it with JQuery).

2) If your controller is called "MaterialController.cs" and if you haven't changed your route configuration, the URL to use is : '/Material/Material'.

3) Your function returns "void". Replace your void by string, or ActionResult. Then, replace your "Response.write" by return "some string".

The problem was in the Ajax call. Here is the solution:

$.ajax({
                url: "Controler/Action",
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                traditional: true,
                data: JSON.stringify({ requiresSetupArray: requiresSetupArray, disabledArray: disabledArray }),
                success: function (data) {
                    button.attr('value', 'Save Checkbox Changes');
                    button.addClass('disabled');
                },
                error: function () {
                    alert("error");
                }
            });

A few things to notice:

  • Stringify is important. Without it, nothing works
  • careful with contentType
  • Carefuly check parameters that the controller is exepecting !

Hope it helps someone in the future!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM