2

i have a user control contains 3 textboxes and a button added to a aspx page . When clicked it should make a ajax call to controller and pass data of textboxes and it should return a message....how can i do this

1 Answer 1

8

Example:

<input type="text" name="foo" id="foo" />
<input type="text" name="bar" id="bar" />
<input type="text" name="baz" id="baz" />
<%= Html.ActionLink("send to controller", "Ajax", "Home", null, new { id = "ajaxLink" }) %>

and in a separate javascript file you could ajaxify this link:

$(function() {
    $('#ajaxLink').click(function() {
        var data = { 
            foo: $('#foo').val(),  
            bar: $('#bar').val(),  
            baz: $('#baz').val()
        };
        $.getJSON(this.href, data, function(result) {
            alert(result.message);
        });
        return false;
    });
});

and the corresponding controller action which will receive the call and return JSON:

public class HomeController: Controller
{
    public ActionResult Ajax(string foo, string bar, string baz)
    {
        // TODO: do something with the arguments

        return Json(
            new { message = "Thanks for sending info" }, 
            JsonRequestBehavior.AllowGet
        );
    }
}

EDIT: Removed the "new" keyword when assigning the value for var data.

Sign up to request clarification or add additional context in comments.

1 Comment

I have copied and pasted this code into template .net mvc 3 project to test and the binding of the variables to foo, bar, baz on the action method Ajax are all coming up as null.

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.