Normally when the result of an action method is successful a redirect happens, maybe that's what you want, especially if your result is not a json result. But if you are returning the same view after your post then you are doing it incorrectly. If the ModelState
is valid on a post, that is if the validation passed (e.g. required fields are supplied), and you add an error message by doing ModelState.AddModelError(("", "Data successfully saved.")
then you are making the ModelState
go into an invalid state. That is the reason why you have the red color.
Now assuming you really want to return the same view then I suppose you have something like:
[HttpPost]
public ActionResult YourActionMethod(YourModel model)
{
// some code goes here
ModelState.AddModelError(("", "Data successfully saved.")
return View(", model);
}
What you should have instead is something like this:
[HttpPost]
public ActionResult YourActionMethod(YourModel model)
{
// some code goes here
ViewBag.SuccessMessage = "Data successfully saved.";
return View(", model);
}
Then on your view something like:
@Html.ValidationSummary(true)
if (!string.IsNullOrWhiteSpace(ViewBag.SuccessMessage)) {
<div class="success-summary">
<p>@ViewBag.SuccessMessage</p>
</div>
}
Note that you don't need an additional @
before the if, that code assumes it's inside a form
tag, using @using
. And then for the css:
.success-summary {
color: #3366FF;
}
You can actually use either ViewData or ViewBag. To know more about the difference of the two you can visit this SO page.
UPDATE:
[HttpPost]
public ActionResult YourActionMethod(YourModel model)
{
//
If (ModelState.IsValid) {
@ViewBag.IsModelValid = true;
ModelState.AddModelError("", "Data successfully saved.");
return View(model);
}
ViewBag.SuccessMessage = "Data successfully saved.";
return View(", model);
}
Your view:
@Html.ValidationSummary(false, "", new { @class= (ViewBag.IsModelValid!=null && ViewBag.IsModelValid) ? "success-summary" : "" })