I'm trying to make use of the IValidatableObject as described here http://davidhayden.com/blog/dave/archive/2010/12/31/ASPNETMVC3ValidationIValidatableObject.aspx.
But it just wont fire when I'm trying to validate, the ModelState.IsValid is always true.
Here is my model code:
[MetadataType(typeof(RegistrationMetaData))]
public partial class Registration : DefaultModel
{
[Editable(false)]
[Display(Name = "Property one")]
public int PropertyOne { get; set; }
}
public class RegistrationMetaData :IValidatableObject
{
[Required(ErrorMessage = "Customer no. is required.")]
[Display(Name = "Customer no.")]
public string CustomerNo { get; set; }
[Display(Name = "Comments")]
public string Comments { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (new AccountModel().GetProfile(CustomerNo) == null)
yield return new ValidationResult("Customer no. is not valid.", new[] { "CustomerNo" });
}
}
I extend a LINQ to SQL table called Registration, my first guess was that this is not possible to do on a Meta class, but I'm not sure?
I do not get any errors, and it builds just fine, but the Validate method will not fire. What have I missed?
That's because it is the Registration model that should implement IValidatableObject and not RegistrationMetaData:
[MetadataType(typeof(RegistrationMetaData))]
public partial class Registration : IValidatableObject
{
[Editable(false)]
[Display(Name = "Property one")]
public int PropertyOne { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (new AccountModel().GetProfile(CustomerNo) == null)
yield return new ValidationResult("Customer no. is not valid.", new[] { "CustomerNo" });
}
}
public class RegistrationMetaData
{
[Required(ErrorMessage = "Customer no. is required.")]
[Display(Name = "Customer no.")]
public string CustomerNo { get; set; }
[Display(Name = "Comments")]
public string Comments { get; set; }
}
Related
Again...
I am doing a MVC with EF5 App. I have a Users Entity, that EF bind with Users table in Database... Looks like this.
public partial class Users
{
public long User_id { get; set; }
[Required]
[StringLength(30, ErrorMessage = "LastName cannot be longer than 30 characters.")]
public string LastName { get; set; }
[Required]
[StringLength(30, ErrorMessage = "Name cannot be longer than 30 characters.")]
public string Name { get; set; }
public int ProcessState_id { get; set; }
public string Sex { get; set; }
[Required,Range(1, int.MaxValue, ErrorMessage = "El País es Obligatorio")]
public int Country_id { get; set; }
[Required]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
public System.DateTime CreationDate { get; set; }
public Nullable<System.DateTime> UpDateTime { get; set; }
[RegularExpression(#"^.{5,}$", ErrorMessage = "Minimum 3 characters required")]
[Required]
[StringLength(9, MinimumLength = 3, ErrorMessage = "Password cannot be longer than 9 characters.")]
public string Password { get; set; }
public string Url { get; set; }
public byte[] Picture { get; set; }
public string CodArea { get; set; }
public string PhoneNumber { get; set; }
public virtual Countries Countries { get; set; }
public virtual ProcessStates ProcessStates { get; set; }
public virtual States States { get; set; }
[NotMapped] // Does not effect with your database
[RegularExpression(#"^.{5,}$", ErrorMessage = "Minimum 3 characters required")]
[StringLength(9, MinimumLength = 3, ErrorMessage = "Confirm Password cannot be longer than 9 characters.")]
[Compare("Password")]
public virtual string ConfirmPassword { get; set; }
}
I have a Model Class that i use it in my Create View....
public class UserViewModel
{
public Users user { get; set; }
public IList<SelectListItem> AvailableCountries { get; set; }
}
My Create Method in the Controller gets a UserViewModel instance...
My Create Method looks like this.
public async Task<ActionResult> Create(UserViewModel model, System.Web.HttpPostedFileBase image = null)
{
try
{
if (ModelState.IsValid)
{
model.user.ProcessState_id = Security.WAITING;
model.user.Rol_id = Security.ROL_PUBLIC;
model.user.CreationDate = DateTime.Now;
model.user.IP = Request.UserHostAddress;
model.user.Url = UserValidation.EncriptacionURL(model.user.Email);
if (image != null)
{
// product.ImageMimeType = image.ContentType;
model.user.Picture= new byte[image.ContentLength];
image.InputStream.Read(model.user.Picture, 0, image.ContentLength);
}
_db.Users.Add(model.user);
_db.SaveChanges();
return RedirectToAction("Create");
}
model.AvailableCountries = GetCountries();
return View(model);
}
catch (RetryLimitExceededException /* dex */)
{
}
return View(model);
}
So far so good.
For my Edit View, i need less properties from User class, so I have a new class with the properties I need. This class is called UserEditView.
public class UserEditView
{
public long User_id { get; set; }
[Required]
[StringLength(30, ErrorMessage = "LastName cannot be longer than 30 characters.")]
public string LastName { get; set; }
[Required]
[StringLength(30, ErrorMessage = "Name cannot be longer than 30 characters.")]
public string Name { get; set; }
[Required, Range(1, int.MaxValue, ErrorMessage = "El País es Obligatorio")]
public int Country_id { get; set; }
[Required]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
public Nullable<System.DateTime> UpDateTime { get; set; }
public byte[] Picture { get; set; }
public string CodArea { get; set; }
public string PhoneNumber { get; set; }
public virtual Countries Countries { get; set; }
}
I also create a new Model for Edit View, called UserEditViewModel and looks like this.
public class UserEditViewModel
{
public UserEditView user { get; set; }
public IList<SelectListItem> AvailableCountries { get; set; }
}
On my Edit method, I use Mapper to bind User entity with UserEditView
public ViewResult Edit(int User_id=3)
{
Users users = _db.Users
.FirstOrDefault(p => p.User_id == User_id);
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Users, UserEditView>();
});
IMapper mapper = config.CreateMapper();
UserEditView userEditView = mapper.Map<Users, UserEditView>(users);
var model = new UserEditViewModel
{
user = userEditView,
AvailableCountries = GetCountries(),
};
return View(model);
}
My problem arise when I want to Update the User table.
The Edit method gets UserEditViewModel instance.
public async Task<ActionResult> Edit(UserEditViewModel model, System.Web.HttpPostedFileBase image = null)
{
try
{
if (ModelState.IsValid)
{}
}
}
UserEditViewModel has an instance of UserEditView but I need an instance of Users in order to EF updates Users Table.
I need to Map again?
How can I get a Users Instance?
I add the following Class
public static class AutoMapperBootStrapper
{
public static void BootStrap()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Users, UserEditView>();
cfg.CreateMap<UserEditView, Users>();
});
IMapper mapper = config.CreateMapper();
}
And I add in my Global.asax
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AutoMapperBootStrapper.BootStrap();
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
then in the controller... i do
public ViewResult Edit(int User_id=3)
{
Users users = _db.Users.FirstOrDefault(p => p.User_id == User_id);
UserEditView userEditView = Mapper.Map<Users, UserEditView>(users);
}
But Mapper.Map have an error... it says Mapper is not instantiated.
the problem is because I defined more than one Mapper. If i define just one, it Works fine...
I need to Map again? How can I get a Users Instance?
You could get the User model from your database using the id and then map the properties that you need to be updated from the view model:
[HttpPost]
public ActionResult Edit(UserEditViewModel model, HttpPostedFileBase image = null)
{
if (!ModelState.IsValid)
{
// Validation failed => redisplay the Edit form so that the
// user can correct the errors
return View(model);
}
var user = _db.Users.FirstOrDefault(p => p.User_id == model.user.User_id);
if (user == null)
{
// no user with the specified id has been found in the database =>
// there's nothing to update
return NotFound();
}
// This will map only the properties of the user object that
// are part of the view model
Mapper.Map<Users, UserEditView>(model.user, user);
// at this stage you could manually update some properties that
// have not been mapped such as the uploaded image
// finally persist the changes to the database
_db.SaveChanges();
// redirect to some other action to show the updated users
return RedirectToAction("users");
}
Also the code you have shown in your question:
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Users, UserEditView>();
});
IMapper mapper = config.CreateMapper();
This is absolutely NOT something that you should be doing inside a controller action. AutoMapper mappings should be configured only once per application lifetime, ideally when your application starts, i.e. for a web application that would be Application_Start in Global.asax. In a controller action you should only use the already configured mappings. I strongly recommend you going through the AutoMapper's documentation for getting better understanding of how to use this framework.
Quote from the documentation:
Where do I configure AutoMapper?
If you're using the static Mapper method, configuration should only
happen once per AppDomain. That means the best place to put the
configuration code is in application startup, such as the Global.asax
file for ASP.NET applications. Typically, the configuration
bootstrapper class is in its own class, and this bootstrapper class is
called from the startup method. The bootstrapper class should call
Mapper.Initialize to configure the type maps.
New to MVC. When I try to add a user to the database using Entity Framework Database First I get this exception:
An exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
This is the code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(RegisterViewModel account)
{
if (ModelState.IsValid)
{
using (db)
{
bool duplicate = db.Users.Any(a => a.UserName == account.UserName);
if (duplicate)
{
ModelState.AddModelError("", "Username already exists in database!");
}
else
{
db.Users.Add(new StoreFront.Models.User { UserName = account.UserName, Password = account.Password, EmailAddress = account.EmailAddress, IsAdmin = false, DateCreated = DateTime.Now });
db.SaveChanges();
ModelState.Clear();
ModelState.AddModelError("RegisterSuccess", "Successfully registered!");
}
}
}
return View();
}
I have validation in my RegisterViewModel for all fields, and when I debug, IsValid = true, otherwise it wouldn't run anyway. Any help would be greatly appreciated...I have been struggling with this for a while.
P.S. Yes the password is currently being stored as a string, this is just a test project that won't be used in the real world.
EDIT: Added Models:
User Model from database:
public partial class User
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public User()
{
this.Addresses = new HashSet<Address>();
this.Orders = new HashSet<Order>();
this.ShoppingCarts = new HashSet<ShoppingCart>();
}
public int UserID { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string EmailAddress { get; set; }
public Nullable<bool> IsAdmin { get; set; }
public Nullable<System.DateTime> DateCreated { get; set; }
public string CreatedBy { get; set; }
public Nullable<System.DateTime> DateModified { get; set; }
public string ModifiedBy { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Address> Addresses { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Order> Orders { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<ShoppingCart> ShoppingCarts { get; set; }
}
Partial Model to add ConfirmPassword:
namespace StoreFront.Models
{
[MetadataType(typeof(RegisterViewModel))]
public partial class User
{
[DisplayName("Confirm Password")]
[DataType(DataType.Password)]
[Compare("Password", ErrorMessage = "Passwords must match")]
public string ConfirmPassword { get; set; }
}
}
RegisterViewModel:
public class RegisterViewModel
{
public int UserID { get; set; }
[DisplayName("Username")]
[Required(ErrorMessage = "Username is required")]
public string UserName { get; set; }
[DisplayName("Password")]
[DataType(DataType.Password)]
[Required(ErrorMessage = "Password is required")]
public string Password { get; set; }
[DisplayName("Confirm Password")]
[DataType(DataType.Password)]
[Compare("Password", ErrorMessage = "Passwords must match")]
public string ConfirmPassword { get; set; }
[DisplayName("Email")]
[Required(ErrorMessage = "Email is required")]
[RegularExpression(#"^([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$",
ErrorMessage = "Please enter a valid email")]
public string EmailAddress { get; set; }
public Nullable<bool> IsAdmin { get; set; }
public Nullable<System.DateTime> DateCreated { get; set; }
}
Fix: When I looked up a tutorial about MVC it asked em to create a partial class and a meta class. That was for code first I believe, which basically made it a new field that my database didn't have a spot for, and I am using database first. So I removed the deleted the partial class for User and it stopped making ConfirmPassword an actual field in the database.
Don't know the real works of it, or if what I said makes sense, but I hope this helps someone eventually.
Remove
[RegularExpression(#"^([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$",
ErrorMessage = "Please enter a valid email")]
from RegisterViewModel
I have a custom class as:
public class BasicInfo
{
[Required(ErrorMessage = "First Name is required.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name is required.")]
public string LastName { get; set; }
}
public class ContactInfo
{
[Required(ErrorMessage = "Cell # is required.")]
public string CellNo { get; set; }
[Required(ErrorMessage = "Email is required.")]
public int Email { get; set; }
}
public class PErson
{
public BasicInfo bInfo { get; set; }
public ContactInfo cInfo { get; set; }
}
and using this code to validate - taken from: How does one do property validation of a C# class using Data Annotations in .NET Framework 3.5?
public static class Validator
{
// This could return a ValidationResult object etc
public static IEnumerable<string> Validate(object o)
{
Type type = o.GetType();
PropertyInfo[] properties = o.GetType().GetProperties();
foreach (var propertyInfo in properties)
{
object[] customAttributes = propertyInfo.GetCustomAttributes(typeof(ValidationAttribute), inherit: true);
foreach (var customAttribute in customAttributes)
{
var validationAttribute = (ValidationAttribute)customAttribute;
bool isValid = validationAttribute.IsValid(propertyInfo.GetValue(o, BindingFlags.GetProperty, null, null, null));
if (!isValid)
{
yield return validationAttribute.ErrorMessage;
}
}
}
}
}
This code works when my class is:
public class PErson
{
[Required(ErrorMessage = "First Name is required.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name is required.")]
public string LastName { get; set; }
[Required(ErrorMessage = "Cell # is required.")]
public string CellNo { get; set; }
[Required(ErrorMessage = "Email is required.")]
public int Email { get; set; }
}
I am trying to do a bit of a custom error handler. We have 4 tabs (using JQuery tabs), they are all build from one large model. Say for simplicity the model looks like:
myModel.HomeInfo
myModel.PhoneNumbers
myModel.Addresses
myModel.PersonalDetails
Each part is an object that have various bits of information. They all have attributes on them and validate messages.
At the top of the page (above the tabs) I want to display some top level errors, by that I mean the errors for attributes on the "myModel" object. This works when I do the:
foreach (ModelState state in viewData.ModelState.Values)
When I do:
#Html.ValidationSummary(false)
on my view I get all errors from each of the four objects and all their children, (more than 10). But when I go through the errors my self, (code above), I only get 2 errors, (the errors for "myModel" only, not its child properties).
I tried to use ILSPY to see what the validation summary is doing and replicate it. Believe I had the code pretty much line for line, but it still only got the two errors.
I do not know what magic is going on when I use the #Html.ValidationSummary().
What I want to know is how I can get all the errors for the whole object my self to be able to display some of the errors on each tab.
for clarification here is my basic model:
public class MemberProfileModel
{
[CompanyTabValid]
public CompanyInformationModel CompanyInformation { get; set; }
[ContactTabValid]
public ContactInformationModel ContactInformation { get; set; }
[InvoiceTabValid]
public InvoiceInformationModel InvoiceInformation { get; set; }
[TabProductIdentificationMarkValid]
public ProductIdentificationMarkModel ProductIdentificationMark { get; set; }
}
public class CompanyTabValid : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext context)
{
var model = value as CompanyInformationModel;
if(model == null) throw new ArgumentNullException("value");
var failed = new ValidationResult("Company information incomplete.");
return model.IsValid ? ValidationResult.Success : failed;
}
}
public class ContactInformationModel : BaseModel
{
public ContactInformationModel()
{
PrimarySiteAddress = new AddressInformation();
PrimarySiteContact = new ContactInformation();
RegisteredOfficeAddress = new AddressInformation();
RegisteredOfficeContact = new ContactInformation();
}
public override void Validate()
{
IsValid = PrimarySiteAddress.IsValid &&
PrimarySiteContact.IsValid &&
RegisteredOfficeAddress.IsValid &&
RegisteredOfficeContact.IsValid;
}
public AddressInformation PrimarySiteAddress { get; set; }
public ContactInformation PrimarySiteContact { get; set; }
public AddressInformation RegisteredOfficeAddress { get; set; }
public ContactInformation RegisteredOfficeContact { get; set; }
}
public class AddressInformation : BaseModel
{
public int Id { get; set; }
public Guid MemberId { get; set; }
/// <summary>
/// This property is only here to make EF happy, do not use
/// </summary>
public int LocationTypeValue { get; set; }
public LocationType LocationType { get { return (LocationType) LocationTypeValue; } set { LocationTypeValue = (int) value; } }
[Required(AllowEmptyStrings = false, ErrorMessage = "Address Line 1 required.")]
[Display(Name = "Address Line 1 *")]
public string AddressLine1 { get; set; }
[Display(Name = "Address Line 2")]
public string AddressLine2 { get; set; }
[Display(Name = "Address Line 3")]
public string AddressLine3 { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "Town required.")]
[Display(Name = "Town *")]
public string Town { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "County required.")]
[Display(Name = "County *")]
public string County { get; set; }
[Display(Name = "Country *")]
public string Country { get; set; }
[RequiredOneOfTwo("InterationalPostCode", ErrorMessage="PostCode or international PostCode are required.")]
[Display(Name = "Post Code *")]
public string PostCode { get; set; }
[RequiredOneOfTwo("PostCode", ErrorMessage = "International PostCode or PostCode are required.")]
[Display(Name = "International Post Code *")]
public string InterationalPostCode { get; set; }
public override void Validate()
{
if (string.IsNullOrEmpty(AddressLine1))
{
this.IsValid = false;
return;
}
else if (string.IsNullOrEmpty(Town))
{
this.IsValid = false;
return;
}
else if (string.IsNullOrEmpty(County))
{
this.IsValid = false;
return;
}
else if (string.IsNullOrEmpty(Country))
{
this.IsValid = false;
return;
}
else if (string.IsNullOrEmpty(PostCode) && string.IsNullOrEmpty(InterationalPostCode))
{
this.IsValid = false;
return;
}
this.IsValid = true;
return;
}
}
I have shown an example of a validation attribute (some of ours are custom, some are normal), the top level MemberProfileModel = myModel in this example, and ContactInformationModel is one of its children which in turn has its own objects such as AddressInformation.
Thanks
I found out why this wasn't working for me. As usual it was me being silly. Because the model has multiple layers / levels to it, I.e. model.someobject.someotherobject.someproperty, when I called tryValidateModel it would validate the top level but not the inner layers.
The solution to this was to ensure they are all called:
TryValidateModel(mp);
TryValidateModel(mp.ContactInformation.PrimarySiteAddress);
TryValidateModel(mp.ContactInformation.RegisteredOfficeAddress);
So my solution is to either create a method to call try validate on each object level or create a refelctive method to do it for me.
In the post event of your page, in the controller just add this:
[HttpPost]
public ActionResult Create(TestViewModel testViewModel)
{
// If not Valid
if (!ModelState.IsValid)
{
return this.View(testViewModel)
}
...
}
And don't forget to add your required and/or other validation to your viewmodel access methods:
[Required(ErrorMessageResourceType = typeof(Resources.MyProject), ErrorMessageResourceName = "validation_Test")]
public virtual string HomeInfo { get; set; }
And in your view:
<div class="editor-row">
<div class="editor-label">
#Html.LabelFor(model => model.HomeInfo)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.HomeInfo)
#Html.ValidationMessageFor(model => model.HomeInfo)
</div>
</div>
I got this from here:
http://www.unknownerror.org/opensource/aspnet/Mvc/q/stackoverflow/1352948/how-to-get-all-errors-from-asp-net-mvc-modelstate
public static List<string> GetErrorListFromModelState
(ModelStateDictionary modelState)
{
var query = from state in modelState.Values
from error in state.Errors
select error.ErrorMessage;
var errorList = query.ToList();
return errorList;
}
Hi I have an Invoice type like:
public class Invoice : IEntity, IValidatableObject
{
public virtual int Id { get; set; }
[Required(ErrorMessage = "Invoice Number is a required field.")]
[Display(Name = "Invoice Number:")]
public virtual string InvoiceNumber { get; set; }
[Required(ErrorMessage = "Invoice Date is a required field.")]
[Display(Name = "Invoice Date:")]
[DataType(DataType.Date)]
public DateTime? InvoiceDate { get; set; }
[Required(ErrorMessage = "Organisation is a required field.")]
[Display(Name = "Organisation:")]
public int OrganisationId { get; set; }
[Required(ErrorMessage = "Region is a required field.")]
[Display(Name = "Region:")]
public virtual int? AreaId { get; set; }
[Required(ErrorMessage = "Total (Exc. GST) is a required field.")]
[Display(Name = "Total (Exc. GST):")]
public decimal? TotalExcludingGst { get; set; }
[Required(ErrorMessage = "Total (Inc. GST) is a required field.")]
[Display(Name = "Total (Inc. GST):")]
public decimal? TotalIncludingGst { get; set; }
public virtual string CreatedByUserName { get; set; }
public virtual DateTime CreatedDateTime { get; set; }
public virtual string LastModifiedByUserName { get; set; }
public virtual DateTime? LastModifiedDateTime { get; set; }
// Navigation properties
public virtual Area Area { get; set; }
public virtual Organisation Organisation { get; set; }
public virtual ICollection<InvoiceLine> InvoiceLines { get; set; }
#region IValidatableObject Members
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if ((TotalExcludingGst + (TotalExcludingGst * .15m)) != TotalIncludingGst) {
yield return new ValidationResult("The total (exc. Gst) + Gst does not equal the total (inc. Gst).");
}
}
#endregion
What I want to do is make sure on insert update that the combination of Organsation and InvoiceNumber is unique.
I'm considering something like:
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var repository = new Repository<Invoice>();
if(!repositoy.CheckUnique(Id)) {
yield return new ValidationResult("The combination of Organisation and Invoice number is already in use");
}
}
Is this bad practise? To be instantiating the repository inside the model?
Is there a better way?
Your solution is not work correctly in a multi user scenario. Because between checking whether an ID exists and saving changes another record maybe inserted with that same ID.
You can create a Unique Constraint on your table. This is the safe way to ensure duplicates are not created.
Current versions of EF does not model/support Unique Constraints. However what you can do is catch the specific exception and check the error message. Then show the errors
try
{
//updation logic
context.SaveChanges();
}
catch (System.Data.DataException de)
{
Exception innerException = de;
while (innerException.InnerException != null)
{
innerException = innerException.InnerException;
}
if (innerException.Message.Contains("Unique_constraint_name"))
{
ModelState.AddModelError(string.Empty, "Error Message");
return;
}
ModelState.AddModelError(string.Empty, "Error Message");
return View();
}
If you are using ASP.NET Web forms you can check this answer