Jay Gould Jay Gould - 3 years ago 76
ASP.NET (C#) Question

ASP.NET MVC showing a hidden div after form submission if object already exists

I have a form in which a user can create a

Project
, and the model validates on
[HttpPost]
just fine.

The following validation from my
Create
Action is what I'm currently using:

if (ModelState.IsValid)
{
var alreadyExists = db.Projects.FirstOrDefault(p => p.Name == project.Name) ?? db.Projects.FirstOrDefault(p => p.ID== project.ID);

if (alreadyExists != null) // If a project with the same name exists
{
return View(project);
}

db.Projects.Add(project);
db.SaveChanges();
return View(project);
}


Currently if the project
Name
or
ID
already exists, it just returns the row with those values from Entity Framework with no notification to the user. I'd like to create some form of alert that tells the user, after POST, that the project they've tried to create already exists.

I wrote a
PartialView
and put the code in
_Create.cshtml
:

<div class="alert alert-danger">
<strong>Error!</strong> A project with that name or ID already exists!
</div>


And the following at the top of my form in
Create.cshtml
:

@Html.Partial("_Create", Model)


and updated my
Create
controller to return the
PartialView
:

var alreadyExists = db.Projects.FirstOrDefault(p => p.Name == project.Name) ?? db.Projects.FirstOrDefault(p => p.TAF == project.TAF);

if (alreadyExists != null) // If a project with the same name exists
{
return PartialView(project);
}


But the bootstrap alert is always showing, even before POSTing the form to the controller.

How can I make the alert show only after a POST if the EF database already contains a record with the same properties?

Answer Source

You could pass a ViewBag property in the POST method to indicate if there was an error, for example ViewBag.Error = true; and then in the view, test if it exists

@if(ViewBag.HasError != null)
{
    @Html.Partial("_Create", Model)
}

Howevere, MVC already has this functionality built in. In the POST method, you can add a ModelState error

if (alreadyExists != null)
{
    ModelState.AddModelError("", "your error message");
}

and that message will be displayed in the @Html.ValidationSummary() placeholder in your view.

Note that if your want the message associated with a specific property, you can use ModelState.AddModelError("YourPropertyName", "your error message"); and it will be displayed in the @Html.ValidationMessageFor(m => m.YOurPropertyName)

You can also consider using the RemoteAttribute to give you client side validation - refer How to: Implement Remote Validation in ASP.NET MVC

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download