c# - Returning a validation error -
i have logincontroller
. loginmodel
able provide validation on string lengths , required fields. displayed fine in 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 want throw own validation message or otherwise //give feedback login 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 - not check on public computer")] public bool notpublicpc { get; set; } }
how throw own validation error - i.e. want show message when login fails. though appreciate validation required , length done in browser different.
i have tried throwing exception
, system.componentmodel.dataannotations.validationexception
if throw exception not handled client receive http 500 error (unless throw httpexception
, specify error number). if desireable thats can do. otherwise can try add error message model state:
modelstate.addmodelerror("propertyname", "error message");
Comments
Post a Comment