Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions RazorPages/models/ModelStateError/Pages/Contacts/Create.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,24 @@ public async Task<IActionResult> OnPostAsync()
{
// Attach Validation Error Message to the Model on validation failure.

// <snippet_5>
if (Contact.Name == Contact.ShortName)
{
ModelState.AddModelError("Contact.ShortName",
"Short name can't be the same as Name.");
}
// </snippet_5>

if (_context.Contact.Any(i => i.PhoneNumber == Contact.PhoneNumber))
{
ModelState.AddModelError("Contact.PhoneNumber", "The Phone number is already in use.");
ModelState.AddModelError("Contact.PhoneNumber",
"The Phone number is already in use.");
}
if (_context.Contact.Any(i => i.Email == Contact.Email))
{
ModelState.AddModelError("Contact.Email", "The Email is already in use.");
}
if (Contact.Name == Contact.ShortName)
{
ModelState.AddModelError("Contact.ShortName", "Short name can't be the same as Name.");
}

if (!ModelState.IsValid || _context.Contact == null || Contact == null)
{
// if model is invalid, return the page with the model state errors.
Expand Down
15 changes: 10 additions & 5 deletions mvc/models/ModelStateError/Controllers/ContactsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,19 +55,24 @@ public IActionResult Create()
public async Task<IActionResult> Create([Bind("Id,Name,ShortName,Email,PhoneNumber")] Contact contact)
{
// Attach Validation Error Message to the Model on validation failure.
// <snippet_5>
if (contact.Name == contact.ShortName)
{
ModelState.AddModelError(nameof(contact.ShortName),
"Short name can't be the same as Name.");
}
// </snippet_5>

if (_context.Contact.Any(i => i.PhoneNumber == contact.PhoneNumber))
{
ModelState.AddModelError(nameof(contact.PhoneNumber), "The Phone number is already in use.");
ModelState.AddModelError(nameof(contact.PhoneNumber),
"The Phone number is already in use.");
}
if (_context.Contact.Any(i => i.Email == contact.Email))
{
ModelState.AddModelError(nameof(contact.Email), "The Email is already in use.");
}
if (contact.Name == contact.ShortName)
{
ModelState.AddModelError(nameof(contact.ShortName), "Short name can't be the same as Name.");
}

if (ModelState.IsValid)
{
_context.Add(contact);
Expand Down