MrM
MrM

Reputation: 21989

How to use $.post with button onclick function and not a form?

I would like to access my controller on an onclick. The form is postback set for another function. I know how to post if there was a form. Is there a way to go to the controller without using a form and if so how do I do that?

<% using (Html.BeginForm("OneMethod", "Home", FormMethod.Post, new { id = "formNext" })) { 
<input id="addContent" type="button" onclick="addContent(ind1, ind2)"/>
<% } %>

jquery

function(addContent(ind1, ind2) {
    //post should go to "TwoMethod" and not "OneMethod" but not sure how...
    $.post($(this).attr("action"), $(this).serialize(), function(response) {
        //code
    }, 'json');
}

Upvotes: 1

Views: 6395

Answers (3)

Chris Kooken
Chris Kooken

Reputation: 33880

Here is a nice function i wrote to post it from AJAX.

submitForm("home/twomethod", $("#formNext"),function(e){do stuff});

Which calls:

function sumbitForm(url, DetailsForm, SuccessCallBack)
{
    $.ajax({
        url: url,
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        dataType: "json",
        data: $(DetailsForm).serialize(),
        success: SuccessCallBack,
        error: MyNamespace.handleAjaxError
    });
}

Upvotes: 4

LeftyX
LeftyX

Reputation: 35587

You cal call $.ajax specifying you are going to POST data. As you can see the url property is the controller/action and the data is a collection of fields/property you want to send. I am using JSON here but you can choose a different way.

url: '<%=Url.Action("DoSomething", "Home")%>',
data: { Name: $('#Field1').val(), MiddleName: $('#Field2').val(), Surname: $('#Field3').val() },

VIEW

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <input type="text" id="Field1" name="Field1" value="" /><br />
    <input type="text" id="Field2" name="Field2" value="" /><br />
    <input type="text" id="Field3" name="Field3" value="" /><br />
    <input type="button" id="post_data" name="post_data" value="Save" />

    <script type="text/javascript">
        $(document).ready(function() {

            $('#post_data').click(function() {

                $.ajax({
                    type: 'POST',
                    url: '<%=Url.Action("DoSomething", "Home")%>',
                    data: { Name: $('#Field1').val(), MiddleName: $('#Field2').val(), Surname: $('#Field3').val() },
                    dataType: 'json',
                    beforeSend: function(XMLHttpRequest) {
                        // You can do something before posting data.
                    },
                    complete: function(XMLHttpRequest, textStatus) {
                        var Response = $.parseJSON(XMLHttpRequest.responseText);
                        if ((XMLHttpRequest.responseText == 'false') || (Response.Status == false)) {
                            // FAIL
                        }
                        else {
                            // SUCCESS
                            alert(Response); // Should be true.
                        }
                    }
                });
            });


        });
    </script>

</asp:Content>

My controller returns a boolean but you can change it with an object.

CONTROLLER:

[HttpPost]
public JsonResult DoSomething(string Name, string MiddleName, string  Surname)
{
    return (Json(true, JsonRequestBehavior.DenyGet));
}

Upvotes: 0

Yngve B-Nilsen
Yngve B-Nilsen

Reputation: 9676

yes, you simply do:

$("#some_ID_To_Button").click(function(){
$.post('/home/myaction', $("#formNext").serialize(), function(response) {
        //code
    }, 'json');
});

:)

Upvotes: 3

Related Questions