Posting form without @HTML.Beginform and using Jquery(ajax) in asp.net MVC
asp.net-mvc, c#, jquery
Solution
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.
Problem
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?