Controller message for the view

4

I did this:

[HttpPost]
        public void CadastraUsusario(string _nome, string _usuario, string _email, string _nivel_acesso, bool _ativo)
        {
            using (RupturaEntities db = new RupturaEntities())
            {
                Usuario usu = new Usuario();
                try
                {
                    var retorna_usuario = db.Usuario
                                          .Where(u => u.NM_Usuario == _nome && u.Usuario1 == _usuario)
                                          .Select(d => new { d.NM_Usuario, d.Usuario1 }).ToList();

                    if (retorna_usuario == null)
                    {
                        usu.NM_Usuario = _nome;
                        usu.Usuario1 = _usuario;
                        usu.Email = _email;
                        usu.NivelAcesso = _nivel_acesso;
                        usu.Ativo = _ativo;
                        db.Usuario.Add(usu);
                        db.SaveChanges();
                    }
                    else
                    {
                        ViewBag.MsgError = "Usuário já está cadastrado no sistema.";
                    }
                }
                catch (Exception ex)
                { }
            }
        }

How do I do when my linq returns something, I do not proceed with the insertion and I trigger the message on the user's screen?

    
asked by anonymous 02.09.2014 / 20:28

1 answer

5

Implementing a @helper to send Flash messages to the screen.

I've implemented one like this:

App_Code / Flash.cshtml

I'm assuming you use jQuery for your project:

@helper FlashMessage(System.Web.Mvc.TempDataDictionary tempData) 
{
    var message = "";
    var className = "";
    if (tempData["info"] != null)
    {
        message = tempData["info"].ToString();
        className = "flashInfo";
    }
    else if (tempData["warning"] != null)
    {
        message = tempData["warning"].ToString();
        className = "flashWarning";
    }
    else if (tempData["error"] != null)
    {
        message = tempData["error"].ToString();
        className = "flashError";
    }
    if (!String.IsNullOrEmpty(message))
    {
        <script type="text/javascript">
            $(document).ready(function() {
            $('#flash').html('@message');
            $('#flash').toggleClass('@className');
            $('#flash').slideDown('slow');
            $('#flash').click(function(){$('#flash').toggle('highlight')});
            });
        </script>
    }
}

Views / Shared / _Layout.cshtml

Place a <div> with id = "flash" , which will serve to display the message, plus the call to helper , which will mount a runtime JavaScript in your Layout : p>

<div id="body">
    @Flash.FlashMessage(TempData)
    <div id="flash"></div>
    @RenderSection("featured", required: false)
    <section class="content-wrapper main-content clear-fix">@RenderBody()</section>
</div>

Helpers / FlashHelper.cs

This is an Extension of Controller :

namespace SeuProjeto.Helpers
{
    public static class FlashHelper
    {

        public static void FlashInfo(this Controller controller, string message)
        {
            controller.TempData["info"] = message;
        }
        public static void FlashWarning(this Controller controller, string message)
        {
            controller.TempData["warning"] = message;
        }
        public static void FlashError(this Controller controller, string message)
        {
            controller.TempData["error"] = message;
        }
    }
}

Use

Use the Controller as follows:

this.FlashInfo("Mensagem de Informação.");
this.FlashWarning("Mensagem de Aviso.");
this.FlashError("Mensagem de Erro.")
    
02.09.2014 / 20:36