MaxPayne
MaxPayne

Reputation: 936

How to apply CSS to Html.ValidationSummary at runtime

I am building my first MVC4 website and I would like to show success message when page successfully submitted. I have achieved by using ModelState.AddModelError(("", "Data successfully saved."); but it is showing in the red color. I want to apply different css at runtime based on some conditions.

Thanks.

Upvotes: 3

Views: 16090

Answers (3)

JoshYates1980
JoshYates1980

Reputation: 3636

I recommend using TempData instead of changing validationsummary and @von described it very well. Use bootstrap. You could do something like this:

Controller

[HttpPost]
    public ActionResult ManageUsers(UserViewModel model)
    {
        if (ModelState.IsValid)
        {
            User obj = new User();
            obj.UserName = model.Email;
            obj.FirstName = model.FirstName;
            obj.LastName = model.LastName;
            obj.Email = model.Email;
            obj.Phone = model.Phone;
            obj.Notes = model.Notes;
            obj.Authorized = model.Authorized;
            UserRepository.SaveUser(obj);
            TempData["Success"] = "Yes";
        }
        return View(model);
    }

View

@Html.ValidationSummary()
@if (TempData["Success"] != null)
{
                <div class="alert alert-success">
                    <a href="#" class="close" data-dismiss="alert">&times;</a>
                    <strong>Success!</strong> The User account was created.
                </div>
}

Upvotes: 2

Darrell Lloyd Harvey
Darrell Lloyd Harvey

Reputation: 472

Von, I too appreciate your answer, but I agree with MaxPayne that you didn't quite provide an answer for the question, more of a work around IMO. I too am looking at a way to style the ValidationSummary without the extra baggage of using the ViewBag.

I do agree that you shouldn't return to the same view after a post unless there are errors, but I do believe there are times when one might want to change the ValidationSummary style dynamically without having to use the ViewBag.

So far this is my only lead http://westcountrydeveloper.wordpress.com/2011/07/06/mvc-validation-part-4-styling-the-validation-controls/

I suppose you could use some JQuery to change the element's css attributes based on the Validation response.

var valid = $("#formID").validate().element("#ElementID");
//or
var valid = $('#formID').validate();
// Then use $(".ElementClass").css({}); to change the the style

Upvotes: 0

von v.
von v.

Reputation: 17118

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" : "" })

Upvotes: 0

Related Questions