3

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.

x2.
  • 9,554
  • 6
  • 41
  • 62
MaxPayne
  • 1,028
  • 1
  • 12
  • 19

3 Answers3

1

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>
}
JoshYates1980
  • 3,476
  • 2
  • 36
  • 57
0

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" : "" })
Community
  • 1
  • 1
von v.
  • 16,868
  • 4
  • 60
  • 84
  • I know what you are trying to explain. I think you have not understood my query or I have not explained it so well. Any way thanks for your efforts. I'll try one more time to explain the issue: Let us take an example of the Default Account control generated with the MVC4 Internet template: this is the login method to login: – MaxPayne Mar 20 '13 at 13:05
  • Detail [IMG]http://i45.tinypic.com/b6stiv.png[/IMG] http://i45.tinypic.com/b6stiv.png – MaxPayne Mar 20 '13 at 13:14
  • If you read my answer again you will notice that you need to insert the ViewBag code inside the `if (ModelState.IsValid...`, then do the rest of my suggestion. – von v. Mar 20 '13 at 13:16
  • I have read your answer and I already know this approach, I this approach I have to maintain 1) @viewbag div and 2) ValidationSummary. So why we cannot use single ValidationSummary to show error and success messages. I you are not aware we can show informational messages in validationsummary. I just not getting the method to add dynamic CSS to validationsummary according to conditions. – MaxPayne Mar 20 '13 at 13:25
  • Be assured I know all what you are talking about too ;) Are you aware you can approach your problem as per my suggestion and you can do it another way too? I prefer to have it separate so the ValidationSummary shows errors and completely have a different element to show a success message. If you know how to use a ViewBag as you've mentioned then you can use it to indicate the success of the post and change the css accordingly. I'll try to update my answer to suit your **preference**. – von v. Mar 20 '13 at 13:30
  • Thanks von v for your efforts. Kindly get back if you found any solution. – MaxPayne Mar 20 '13 at 13:38
0

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