Checkback error returned

I have this LoginController . LoginModel can provide verification of line lengths and required fields. This is clearly visible on the razor page.

 public class LoginController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(LoginModel model) { if (ModelState.IsValid) { if (Membership.ValidateUser(model.Username, model.Password)) { FormsAuthentication.SetAuthCookie(model.Username, model.NotPublicPc); var url = FormsAuthentication.GetRedirectUrl(model.Username, model.NotPublicPc); return Redirect(url); } else { //here I want to throw my own validation message or otherwise //give feedback that the login was unsuccessful } } return View(); } } public class LoginModel { [Required] [StringLength(50, MinimumLength = 4)] public string Username { get; set; } [Required] public string Password { get; set; } [Display(Name = "Keep me logged in - do not check on public computer")] public bool NotPublicPc { get; set; } } 

How can I reset my own validation error - that is, I want to show a message when the login fails. Although I now appreciate the confirmation for the required, and the length is executed in the browser, so this is different.

I tried throwing Exception and System.ComponentModel.DataAnnotations.ValidationException

+4
source share
4 answers

If you throw an exception that is not being handled, the client will receive an http 500 error (unless you throw an HttpException and HttpException error number). If this is desire, then this is what you can do. Otherwise, you can try adding an error message to the model state:

 ModelState.AddModelError("PropertyName", "Error Message"); 
+2
source

Here are some of my code for the Semester example field in ASP.NET MVC:

 [Display(Name = "Semester:"), Required(ErrorMessage = "Please fill in the Semester of the Issue"), StringLength(25)] 

This will specifically cause an error message if the field is empty.

You can also add regular expressions if you want. i.e:

  [RegularExpression(@"^http(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$", ErrorMessage = "Link format is wrong")] 

This code will verify that the URL is in the appropriate format.

This should be very close to what you are looking for, although if it is not, I will be happy to delete my answer.

+1
source

You can do something like

 ModelState.AddModelError(string key, string errorMessage); 
+1
source

You can add a custom error:

 ModelState.AddModelError(String.Empty, "YOUR ERROR"); 

This will add an error with the text “YOUR ERROR” and no related property, which means that it will only be displayed in the check summary. If you add a property name instead of String.Empty , it should be shown as an error of this property.

You can also pass an exception as a second parameter, but I never used it, so I don't know what the result will be ...

+1
source

Source: https://habr.com/ru/post/1495766/


All Articles