title: jQuery ajax login form with asp.net mvc
body: <p>I have a simple login form on my MVC app (note I'm not using the inbuilt one) which looks something like this:</p>
  
  <pre><code>@using (Html.BeginForm())
  {
      &lt;label for="UserName" class="placeholder"&gt;Email address or username&lt;/label&gt;
      @Html.TextBoxFor(m =&gt; m.UserName)
  
      &lt;label for="Password" class="placeholder"&gt;Password&lt;/label&gt;
      @Html.PasswordFor(m =&gt; m.Password)
  
      &lt;button type="submit" title="Log in"&gt;Log in &amp;#9658;&lt;/button&gt;
  }
  </code></pre>
  
  <p>I have some jquery which should post the data using ajax. If the user is correct then send them off to the correct page otherwise show an error. However I'm struggling. Can anyone point me in the right direction as currently I also get the success even if the account details are incorrect and I've lost the redirect functionality on successful login due to the preventdefault.</p>
  
  <pre><code>$('form').live('submit', function (event) {
  
                      // Stop the form from doing a native postback
                      event.preventDefault();
  
                      $.ajax({
                          type: 'POST',
                          timeout: 5000,
                          url: $(this).attr('action'),
                          data: $('form').serialize(),
                          success: function (responseHtml) {
                              // what goes here... as the form is always successful even if the account details are incorrect
                          },
                          error: function (jqXHR, textStatus, errorThrown) {
  
                              alert('error');
                          }
                      });
                  });
  </code></pre>
  
  <p>C#</p>
  
  <pre><code>[HttpGet]
  public ActionResult Login()
  {
      if (Session["UserID"] != null)
      {
          return RedirectToAction("Index", "Home", new { area = "Dashboard" });
      }
  
      return View();
  }
  
  [HttpPost]
  public ActionResult Login(User user, string returnUrl)
  {
      // Validate the email and password
      if (users.Login(user.UserName, user.Password, Request.UserHostAddress))
      {
          FormsAuthentication.SetAuthCookie(user.UserName, true);
  
          if (Url.IsLocalUrl(returnUrl) &amp;&amp; returnUrl.Length &gt; 1 &amp;&amp; returnUrl.StartsWith("/")
              &amp;&amp; !returnUrl.StartsWith("//") &amp;&amp; !returnUrl.StartsWith("/\\"))
          {
              return Redirect(returnUrl);
          }
          else
          {
              return RedirectToAction("Index", "Home", new { area = "Dashboard" });
          }
      }
      else
      {
          return View();
      }
  }
  </code></pre>