Dimo
Dimo

Reputation: 3280

Posting form without @HTML.Beginform and using Jquery(ajax) in asp.net MVC

How can I fill out a form without using @HTML.Beginform and by using JQuery Ajax instead? Right now I tried:

    var postData = { form1: username, form2: password };

    $.ajax({
        type: "POST",
        url: '/Controller/Method',
        data: postData,
        dataType: "json",
        traditional: true
    });

But after posting, the browser does not navigate to the correct view. Of course I have return View() correctly in controller. Using Fiddler I see that it's correctly posted and the response is correct too...

Do I have to use @HTML.Beginform or can I do it with Ajax?

Upvotes: 10

Views: 28499

Answers (3)

Paul
Paul

Reputation: 12440

Your can use either a raw HTML <form> tag or the @HTML.BeginForm helper. Here is an example using just HTML

Complete solution:

<form action"/Controller/Method" method="POST" id="signInForm">
    <input type="text" name="form1" />
    <input type="text" name="form2" />
    <input type="submit" value="Sign in" />
</form>

$( function() {
    $( 'signInForm' ).submit( function( evt ) {
        //prevent the browsers default function
        evt.preventDefault();
        //grab the form and wrap it with jQuery
        var $form = $( this );
        //if client side validation fails, don't do anything
        if( !$form.valid() ) return;
        //send your ajax request
        $.ajax( {
            type: $form.prop( 'method' ),
            url: $form.prop( 'action' ),
            data: $form.serialize(),
            dataType: "json",
            traditional: true,
            success: function( response ) {
                document.body.innerHTML = response;
            }
        });
    });
});

I recommend using @Url.Action to set the URL of your form action. This way routing can generate your URL.

<form action"@Url.Action("Method", "Controller")" method="POST" id="signInForm">
    <input type="text" name="form1" />
    <input type="text" name="form2" />
    <input type="submit" value="Sign in" />
</form>

It is slightly more advanced, but I would try using something like Take Command to manage your jQuery Ajax calls.

Disclaimer, I am a contributor to the TakeCommand project.

Upvotes: 20

Lars Anundsk&#229;s
Lars Anundsk&#229;s

Reputation: 1355

This will do a xhr post to the server and return the view as data (response) It will not navigate, if it returns html, you need to set a proper datatype in your request to tell that you expect html back from the server:

Given your action returns html, you can put the returned html on your page in your success function.

postData = "{'ID':'test'}";
$.ajax({
    type: "POST",
    url: '/Home/Test',
    data: postData,
    dataType: 'html',
    contentType: 'application/json',
    traditional: true,
    success: function (data) {
        $("#yourdomelement").html(data);
    }
});

In your action;

public ActionResult Test([FromBody]PostData id)
{
    return Content("<p>hello</p>");
}

Upvotes: 1

haim770
haim770

Reputation: 49095

When you're using @Html.BeginForm, the HTML output is:

<form method="POST" action="/Controller/Method">

And when you submit that form, the browser handles it just like another page navigation (only using POST method) hence the response is loaded into the parent frame.

But, when you're initiating an Ajax request, it's up to you to handle the response from the server (typically using a callback function).

If you want to simulate the regular form submission behavior, it would be something like:

$.ajax({
    type: "POST",
    url: '/Controller/Method',
    data: postData,
    dataType: "json",
    traditional: true,
    success: function(response)
    {
        document.body.innerHTML = response;
    }
});

This would not replace the entire page content with the response (only the BODY contents) but in most cases it will be fine.

Upvotes: 2

Related Questions