Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8465945
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T15:11:51+00:00 2026-06-10T15:11:51+00:00

I’ve created a simple login form that I’d like to validate via ajax. What’s

  • 0

I’ve created a simple login form that I’d like to validate via ajax.

What’s the most appropriate method to display the server-side validation errors produced by MVC? Is converting the error to a JSON result and stripping out the error message appropriate? If not, then what would be?

Currently what I have is posting correctly, but the entire form comes back. The goal is just to display the server-side errors on the form without a postback/refresh. Thanks in advance…here is my code:

Main View – Login.vbhtml

@ModelType UHCO_MVC_Agency.LoginModel

<div class="error-container">@Html.ValidationSummary(True)</div>
<div class="row-fluid">
    <div class="span12">
        <div id="login-form" class="span6">
            @Using Html.BeginForm()
               @<fieldset>
                  <legend>Log in to your account now</legend>
                  <div class="row-fluid">
                     <div class="span12">
                        @Html.LabelFor(Function(m) m.UserName)
                        @Html.TextBoxFor(Function(m) m.UserName, New With {.class = "span12", .placeholder = "Username"})
                        @Html.ValidationMessageFor(Function(m) m.UserName)
                     </div>
                  </div>
                  <div class="row-fluid">
                     <div class="span12">
                        <label for="Password">Your password</label>
                        @Html.PasswordFor(Function(m) m.Password, New With {.class = "span12", .placeholder = "Password", .type = "password"})
                        @Html.ValidationMessageFor(Function(m) m.Password)
                     </div>
                  </div>
                  <div class="row-fluid">
                     <div class="span12">
                        <label for="RememberMe" class="checkbox clearfix">
                           @Html.CheckBoxFor(Function(m) m.RememberMe)
                           Remember me next time I visit
                        </label>
                     </div>
                  </div>
                  <button type="submit" class="btn btn-primary input-small" value="submit">Log in</button>
               </fieldset>
            End Using
         </div>
      </div>
</div>

Controller – AccountController.vb

<HttpPost()> _
Public Function Login(ByVal model As LoginModel, ByVal Username As String, ByVal Password As String, ByVal returnUrl As String) As ActionResult
   Dim res As New LoginResponse()
   Try
      'login here
   If Not String.IsNullOrEmpty(returnUrl) AndAlso Url.IsLocalUrl(returnUrl) Then
      res.Status = "Success"
      Return RedirectToAction("Welcome", "Account")
   End If
   Catch ex As Exception
      If Not HttpContext.Request.IsAjaxRequest() Then
         ModelState.AddModelError("", ExceptionWrapper.Wrap(ex).ExceptionMessage())
         Return View("Login", model)
      Else
         res.Status = "Failed"
         res.Errors.Add(ExceptionWrapper.Wrap(ex).ExceptionMessage())
         Return Json(res)
      End If
   End Try
   ' If we got this far, something failed, redisplay form
   Return View(model)
End Function

Application.js

$("#login-form form").live().submit(function (e) {
  e.preventDefault();
  alert("ok");
});
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T15:11:52+00:00Added an answer on June 10, 2026 at 3:11 pm

    This is a C# version of the solution. I believe, it should be easy to convert to corresponding VB.NET version

    using JSON is absolutely a nice way to do this.

    First thing. I would change the POST action method to handle my request for Ajax requests and return JSON response back.

    To hold my Error response, I will create a class like this

    public class LoginResponse
    {
      public string Status { set;get;}
      public List<string> Errors { set;get;}
    
      public LoginResponse()
      {
        Errors=new List<string>();   
      }       
    }
    

    And in our POST action method

    [HttpPost]
    public ActionResult Login(LoginModel model)
    {
      if(Request.Ajax)
      {
           var res=new LoginResponse();
         //Do your Validations, If everything is fine send Success JSON
            res.Status="Success";
    
         //else, Lets return a JSON with errors
            res.Status="Failed";
            res.Errors.Add("Email does not exist in Earth and Mars");
            res.Errors.Add("Password contain the word black magic");
    
         return Json (res);
      }
      else
      {
         //Do the normal Processing for Non Ajax requests here
      }
    }
    

    So if there is some error you want to return back to the client, you will send JSON in this format

    {
        "Status": "Failed",
        "Errors": [  "Email does not exist",  "Passoword is worse"  ]
    }
    

    And If everything is fine, We will send JSON like this

    {
        "Status": "Success"
    }
    

    Now in our view, we will get rid of the Ajax form and use the Normal form tag with some pure jQuery.

    @ModelType UHCO_MVC_Agency.LoginModel
    @using(Html.BeginForm())
    {
      //Here your for elements
    
      <input type="submit" id="btnSubmit"/>
    }
    <script type="text/javascript">
    
    $(function(){
       $("#btnSubmit").click(function (e) {
          e.preventDefault();
         $.post("@Url.Action("Login","User")", $("form").serialize(), function (r) {
           if(r.Status=="Success")
           {
             //Login is success . do whatever you want.
           }
           else
           {
             //Lets get the Errors from our JSON
             $.each(r.Errors,function(index,item){
                 //Lets show the error
                  $("#errorSummary").append(item);
             }  
           }
         });
    
    });    
    </script>
    

    EDIT : Change your js code like this and see what happens

    $("#login-form form").live('submit', function(e){
       e.preventDefault();
      //the code
    
    });
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would like my Web page http://www.gmarks.org/math_in_e-mail.txt on my Apache 2.2.14 server to display
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I am doing a simple coin flipping experiment for class that involves flipping a
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I am trying to understand how to use SyndicationItem to display feed which is
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I would like to count the length of a string with PHP. The string

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.