ASP.NET MVC ajax server side validation without using model

I am using a web service and I am accessing it from the BaseController class. I would like to run a server check to check if the login is valid. This way I can send an alert with a message if it is invalid. Warning - the client should. I am new to MVC but know some basics.

I understand the security behind what I ask for. Login is the simplest example I could think of.

Another example.

Let's say I have a contact form. I want to do a server check without refreshing the page. I get that I can post a form using AJAX. I need to return a list of errors and display them on the page. Validation will be done in the web service method called from the controller.

+3


source to share


5 answers


If you really want to pass your username and password to the server controller and get the result in the client script, you can do it like this:

You have an action method in your User Account Controller to check your username password combination like this. You will return Json

actions from the method based on the validation you perform in your method. We are declaring a class called " JsonDataResult

" that you can use to communicate with jSon. This class has two properties. A string property called " Message

" where you can send a message ("Success" / "Errors") and a list of strings to store error messages, if any.

public class JsonDataResult
{
   public string Message { get;set;}
   public List<String> Items = new List<String>();
}

      

and here my action method looks like



  public ActionResult Logon(string userName,string password)
  {
       // check your username password and if there is its not valid, do this
        List<String> errors = new List<String>();
        errors.Add("username is not available");
        errors.Add("password is not nice!");

        var data = new JsonDataResult { Message = "Errors", Items = errors };
        return Json(data);
  }

      

You can set the message value to "Success" if the username and password are correct. You can also skip adding error messages.

Now, from your client script, use jQuery post to send data to Action Method and get jSon result and check value of Message properties. If he says "Errors", walk through each error and show it.

$(function () {
    $("form").submit(function () {
        $.post('@Url.Action("Logon","Account")', { userName: $("#username").val(), password: $("#password").val() }, function (data) {

            if (data.Message == "Errors") {
                $.each(data.Items, function (index) {
                    alert(data.Items[index]);
                });
            }
            else
            {
                // validation is successful.May be you want to redirect now ?
            }
        });
        return false;
    });
});

      

+1


source


Just start your website with AJAX POST with credentials and call this:

FormsAuthentication.SetAuthCookie(userEmail or whatever, true);

      



Then return the JSON result (not a view) and check the result in jQuery code on the website.

+1


source


If you are using a member provider and you need to check if the user can follow him.

 bool isValidLogin = Membership.ValidateUser(UserName, Password);

      

OR try asking for help

 bool isValidLogin = FormsAuthentication.Authenticate(UserName, Password);

      

+1


source


Something like this, although passing the password through an ajax request is probably not a good idea.

Your question is confusing, so here is the basic idea.

CS:

public AuthController
{
        [HttpPost]
        public JsonResult CheckAuthentication(string UserName, string Password)
        {
            return Json(Membership.ValidateUser(UserName, Password));
        }
}

      

JS:

var authChecking = $.post("/Auth/CheckAuthentication", { UserName: username, Password: password });
authChecking.done(function(result) { if (!result) 
    {
        alert("Invalid");
        // or dialog or whatever.
    }
});

      

0


source


At some point, I had to write some custom validation logic for a lot of dynamic content that freely had matching models, but based on the options selected, the validation was different. I'll just copy and paste the code from my app and dumb it, but you can follow the basic example. This also goes for saving multiple forms across multiple tabs .. but works for one too, but you might simplify it. JS is old and can be cleaned up too much with promises and distributed events, but that's a topic for another day.

JS:

$("button#Save").on("click", function () {
            // checks if existing errors have been cleared before trying to submit again
        if ($(".ui-state-error, .ui-state-error-text", "#tabs").length) {
            alert("There are errors on the page. You must correct any errors before saving.");
        }
        else {
                // don't allow to submit twice.. again.. better ways to do this..
            if (!Saving) {
                Saving = true;
                            // show saving message overlay
                $('#CanvasLoading').html("Saving...<span>Loading</span>").show();
                //map data
                            // PASSES IN THE ID OF THE FORM
                var data = $("form.create-item-form", "#tabs").map(function () {
                    var $form = $(this);

                    return {
                        Name: $form.find(":input[name=Name]").val(),
                        FolderName: $form.find(":input[name=FolderName]").val(),
                        ItemName: $form.find(":input[name=ItemName]").val(),
                        ViewId: $form.find(":input[name=ViewId]").val(),
                        FormId: $form.attr("id")
                }).toArray();

                $.ajax(
                {
                    url: Routes.New.SaveAllPost,
                    type: 'POST',
                    contentType: 'application/json',
                    data: { items: data },
                    success: function (resultJSON) {
                        var result = $.parseJSON(resultJSON);
                        if (result.Success) {
                                Saving = false;
                            });
                        }
                        else {
                            $.each(result.Errors, function (i, item) {
     // loops through all items and applies class ui-state-error to inputs in the form with given id
                                var formId = item.FormId;
                                var propertyName = item.FieldName;
                                $.each(item.Errors, function (i, error) {
                                    var id = $("input[name=" + propertyName + "], select[name=" + propertyName + "]", "#" + formId).addClass("ui-state-error").parents("div.ui-tabs-panel:first").attr("id");
                                    $("#li-upload-" + id, "#tabs").addClass("ui-state-error");
                                });
                            });

                               // hide loading overlay
                            $('#CanvasLoading').hide();
                            Saving = false;
                        }
                    }
                });
            }
            else {
                alert("You have already started saving. Please wait for results to process.");
            }
        }
        return false;
    });

      

FROM#:

public class NewController : Controller
    {
[HttpPost]
        public JsonResult SaveAll(List<UploadViewModelDTO> items)
        {
            UploadItemValidationDTO validation = ValidateItems(items);
            if (validation.Success)
            {   
                // validated: do stuff

            }

            return Json(validation);
        }
}

private UploadItemValidationDTO ValidateItems(List<UploadViewModelDTO> items)
        {
            UploadItemValidationDTO validation = new UploadItemValidationDTO();

            // check for errors
            // if error add using following code
            // error has field name and id of form it came from
            validation.Errors.Add
            (
                new Error
                {
                    Errors = new List<string>() { "Folder is required" },
                    FieldName = "FolderName",
                    FormId = item.FormId
                }
            );          

            validation.Success = (validation.Errors.Count < 1);

            return validation;
        }

public class UploadItemValidation
    {
        public UploadItemValidation()
        {
            Errors = new List<Error>();
        }

        public bool Success {get;set;}
        public List<Error> Errors {get;set;}
    }

    public class Error
    {
        public string FormId {get;set;}
        public string FieldName {get;set;}
        public List<string> Errors {get;set;}
    }

      

0


source







All Articles