0
votes

I have a problem when developing a single page web app.

When jQuery send json to HTTPPOST action:

$('#user_dialog .create').click(function () {
                            var user = getInfoUser();
                            $.ajax({
                                url: '@Url.Action("Create", "User")',
                                async: false,
                                type: 'POST',
                                data: JSON.stringify(user),
                                datatype: 'json',
                                contentType: 'application/json;charset=utf-8',
                                success: function (data) {
                                    $('#user_dialog').dialog("close");
                                }
                            });
                        });

My HTTPPOST action in controller will handle the request

[HttpPost]
  public String Create(UserAddViewModel model)
        {
            try
            {
                // TODO: Add insert logic here

                return JsonConvert.SerializeObject(true);
            }
            catch
            {
                return JsonConvert.SerializeObject(false);
            }
        }

And my jQuery success callback function will be fired and data 'true' will be received.

But the problem now is after this, the page will be redirect to /User/Create view page

I don't want it redirect to the page, i just want to handle the UI by my jQuery code.

Is that because it is HTTPPOST action?

What is the actual reason and how to fix it?

1

1 Answers

4
votes

Presumably, the thing you're clicking is a URL. You're not preventing the default event (loading the url) from occuring in your click event

$('#user_dialog .create').click(function (event) {
    event.preventDefault();
    //rest of function

Whenever a click event finishes, the default event (loading a URL if it's a link, submitting a form if it's a submit button, toggling a checkbox, etc.) will occur next. In order to prevent this you must do it explicitly either using preventDefault() or by returning false. See http://api.jquery.com/event.preventDefault/ for the documentation.