3

I've got an MVC 4 app. I have the following JavaScript function that fires whenever a change is made to an element with an Id of 'file'. The submit works fine. However, I would like to submit to a specific action method on the current controller and not the method that is defined in the HTML.BeginForm definition. I'm fairly new to all this and am not sure how to go about doing this.

How can I change this code to submit to a named action method on my controller?

$(function () {
    $("#file").change(function () {
        $("form").submit();
    });
});

1 Answer 1

4

You can set the action before submitting the form:

$(function () {
    $("#file").change(function () {
        $("form").attr("action", '@Url.Action("Action", "Controller")');
        $("form").submit();
    });
});

Update: Based on a clearer understanding of your requirements, if you want the user to stay on the same page when posting via the change event, you can make an ajax post, like this:

$(function () {
    $("#file").change(function () {
        var ajaxData = {
            // initialise your ajax data to pass to post target URL
        };
        $.ajax({
            url: '@Url.Action("Action", "Controller")', // post target URL goes here
            type: 'POST',
            data: ajaxData,
            success: function (data, text) {

            },
            error: function(request, status, error) {

            }
        });
    });
});

There are further options available for ajax calls in the jQuery docs.

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

3 Comments

Yes I could do this, but I want to preserve the original action method for when the user clicks the Submit button. So, essentially, I want to post to one action method on a file change, but a different one (the one defined in the form) when the user clicks the Submit button.
Are you intending for users to stay on the same page if the form is submitted via the change event? If they're not, the post will result in a redirect anyway, so the original action method will still be attached to the form submit button when this page next loads.
Yes, if the form is submitted via the change event, the user will stay on the same page. They will not stay on the same page in the event of a Submit button click.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.