1

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');
}

3 Answers 3

4

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
    });
}
Sign up to request clarification or add additional context in comments.

5 Comments

I'm doing the same thing you are...I just get the url from the form instead of hardcoding it. Don't think I deserve a down vote..
So in this case how would the call know to go to TwoMethod in the controller?
It gets the URL from your form action attribute, for the twoMethod attribute, youll need to provide your own URL. I have modified the answer.
+1 for introducing a new way of doing things... I am having trouble with setting up my namespace in this function but I will look into this one definately, thanks
You can just drop the namespace and create a normal function. I have modified the example to do this.
3

yes, you simply do:

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

:)

Comments

0

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));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.