Search code examples
asp.net-mvc-3child-actions

Want to display a message in layout coming from child action?


I want to display a message in layout coming from child action ? How can i do that ? Like in my layout i have a login form (rendered as a child action).. so when the login fail i would like to show a message in the layout in a specific DIV. The problem is that the layout is probably rendered before the child view. Also there another problem, the layout is rendered by any controller. Any ideas ?


Solution

  • You could put a validation summary in your layout somewhere. (Razor syntax):

    <div>@Html.ValidationSummary(false)</div>

    Then just decorate the viewmodel that is being passed to your login with [Required] attributes.

    public class LoginViewModel
    {
        [Required(ErrorMessage="Please enter a your user name.")]
        public string UserName { get; set; }
    
        [Required(ErrorMessage = "Please your password.")]
        public string Password{ get; set; }
    }
    

    or if you wanted to put a more general error message just leave your viewmodel properties decorated with the [Required] attribute, then in your Login controller, in the POST method do something like this:

    [HttpPost]
    public ActionResult Login(LoginViewModel viewModel)
    {
        if (!ModelState.IsValid)
        {
            ModelState.AddModelError("Error", "Sorry, your login failed, please try again.");
        }
    }
    

    that error will then show up in the validation summary.