Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 227
Dimo Avatar asked Aug 17 '13 21:08

Dimo


People also ask

What is difference between HTML BeginForm and ajax BeginForm?

Html. BeginForm() will create a form on the page that submits its values to the server as a synchronous HTTP request, refreshing the entire page in the process. Ajax. BeginForm() creates a form that submits its values using an asynchronous ajax request.

Why we use HTML BeginForm in MVC?

The Html. BeginForm helper method contains a couple overloads whose intended purpose is to make writing routed forms easier. It is aware of MVC stucture and makes sure its targeting a controller and action.

What is @using HTML BeginForm ()) in MVC?

"BeginForm()" is an extension method for both HtmlHelper and AjaxHelper classes. It returns an MVCForm object from both HtmlHelper and AjaxHelper class instances so there is not much difference but the AjaxHelper method submits the form asynchronously using JavaScript.

What is ajax BeginForm in MVC?

Ajax. BeginForm is the extension method of the ASP.NET MVC Ajax helper class, which is used to submit form data to the server without whole page postback. To work Ajax. BeginForm functionality properly, we need to add the reference of jquery.


3 Answers

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.

like image 116
Paul Avatar answered Oct 06 '22 00:10

Paul


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.

like image 44
haim770 Avatar answered Oct 05 '22 23:10

haim770


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>");
}
like image 27
Lars Anundskås Avatar answered Oct 06 '22 00:10

Lars Anundskås