Controller message to view

Asked

Viewed 1,395 times

4

I did that:

[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 stop when my Inline returns something, I do not proceed with inserting and triggering the message on the user screen?

1 answer

5


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

I implemented one like this:

App_code/Flash.cshtml

I’m guessing 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

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

<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 a 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 inside your Controller the following:

this.FlashInfo("Mensagem de Informação.");
this.FlashWarning("Mensagem de Aviso.");
this.FlashError("Mensagem de Erro.")
  • I haven’t been able to send a controller message to the view and display on the user page.

  • Have you implemented all the steps? What about your code? You inspected the <div id="flash"> when testing?

  • See if that’s it. You created a view called Flash.cshtl. Then in the _Layout.cshtml view you made the appropriate changes. He created a class called Flashhelper.Cs and there inside the controller that in my case, will make the rule and the message, put the 3 lines (Use) that you believe. If that was it, could not make it work, I even tried to create exactly as you said, until the folders I have not created them to look exactly like you put here.

  • You can update the question with the implemented code?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.