Displaying message in a view through the C# MVC Controller

Asked

Viewed 5,562 times

6

looking for a solution I found a way in the link Controller message to view

But my problem is that nothing is shown. I don’t know if it’s because I don’t have an action in the View but the message doesn’t appear.

The structure is mounted in this way (the base structure of the previous link has been maintained and mounted practically equal):


Controller

public ActionResult Relatorios()
        {
            ViewBag.Message = "Mensagem";
            ViewBag.TipoUser = 1;

            this.FlashInfo(this, "Mensagem de Informação.");
            this.FlashWarning("Mensagem de Aviso.");
            this.FlashError("Mensagem de Erro.");
        }

Inside the View I only have the following code:


@model dynamic

@{
    ViewBag.Title = "Relatórios";
    Layout = "~/Areas/Admin/Views/Shared/_Layout.cshtml";
}

Report Management

Within _Layout placed within the following segment

<div class="container-fluid" style="margin-left: 10px; margin-right:5px; margin-bottom: 10px; margin-top: 10px">
    @Flash.FlashMessage(TempData)
    <div id="flash">
    </div>  
    @RenderBody()
    <hr/>
    <footer style="margin-top: 10px">
       <p>&copy; @DateTime.Now.Year - Empresa</p>
    </footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/jqueryui")
@Scripts.Render("~/bundles/site")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/bundles/inputmask")
@Scripts.Render("~/bundles/maskedinput")
@RenderSection("scripts", required: false)
</body>
</html>

Someone can help me?

  • You want to write the content of ViewBag.Message on your page? if it is just put @ViewBag.Messagein the view. I don’t quite understand what you want.

  • In fact, I set up the structure offered by the link attached, everything works "apparently" by debug has no error, but also does not present the message. I do not know if it is because the controller does not have an action or Submit but I did a test including this and still did not present the message.

  • Did you inspect the HTML content to see if the message was written to it? It might just be a display problem.

  • Do what @Gypsy said. If you still don’t find it, you can do another test, you see that @DateTime.Now.Year there at the end of Layout? Do you see it in HTML? If you see it, put the @ViewBag.Message right next to it. The message should appear pasted on the date, at least it will give you a light on how the view works

  • When I put Viewbag.Message next to @Datetime it worked, but the Flashinfo method for example does not appear. Imagine that I have several actions inside the controller and at the end I would like to present a message like Alert with the information Flashinfo ("Process performed successfully"), inside the controller not passing the Viewbag or something similar but presenting the message, so I saw the topic and did the implementation.

  • Trying to resolve the situation, I tried to take the <div = "></div" to the view and Flash.Flashmessage(Tempdata) to the view by removing it from _Layout and it didn’t work either. Nothing is shown. It’s like he’s ignoring the helper’s javascript. I think !

  • Doing the debug, I could notice that it enters Flash.cshtml, tests the content and passes stating that it is not null, processes the javascript and returns to view, then it processes the _Layout and when finished it shows nothing.

Show 2 more comments

1 answer

3

There are some ways. I implemented a very simple solution and you can access it through this .net fiddle

For limitations of the tool I did not use inheritance, which I strongly recommend the use.

Feel free to extend this simple solution.

I hope I’ve helped.

Update: I’ll put the code here to avoid future problems like breaking dotnetfiddle link, but for viewing/running online I will keep the .net fiddle

Mydialog.Cs

namespace MyDialogMvcApp
{
    public class MyDialog
    {
        public enum DialogType : short {
            Info = 0,
            Success = 1,
            Warning = 2,
            Error = 3
        }

        public string Title { get; set; }
        public string Content { get; set; }
        public DialogType @Type { get; set; }

        public override string ToString() => $"{{ \"title\": \"{Title}\", \"content\": \"{Content}\", \"type\": \"{@Type.ToString().ToLower()}\" }}";
    }
}

Basecontroller.Cs

using System;
using System.Web.Mvc;

namespace MyDialogMvcApp
{
    public abstract class BaseController : Controller
    {
        public const string SystemMessage = "MY_DIALOG";

        protected void ShowMessage(string htmlContent, string htmlTitle = "Mensagem do Sistema", MyDialog.DialogType type = MyDialog.DialogType.Info)
        {
            this.ShowMessage(new MyDialog{ Title = htmlTitle, Content = htmlContent, @Type = type});
        }

        protected void ShowMessage(MyDialog dialog)
        {
            this.TempData[SystemMessage] = dialog.ToString(); 
        }
    }
}

Homecontroller.Cs

using System;
using System.Web.Mvc;

namespace MyDialogMvcApp
{
    public class HomeController : BaseController
    {
        [HttpGet]
        public ActionResult Index()
        {
            this.ShowMessage("Uma mensagem de teste =)");
            return View();
        }
    }
}

Index.cshtml or _Layout.cshtml (with @Renderbody())

@{  Layout = null; }

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Bootstrap 101 Template</title>

        <!-- CSS Includes -->
        <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
        <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css">

    </head>

    <body>
        <div class="container">
            <div class="col-md-6 col-md-offset-3">
                <h1>E ai, cara!?</h1>
                <p>Espero que você tenha recebido um alerta quando a página carregou. ;)</p>
                <p>Caso não tenha notado, <a href="javascript:void(0);" id="aShowMessage">clique aqui</a> para que a mensagem seja exibida novamente.
            </div>
        </div>

        <!-- JS includes -->
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
        <script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>


        <script type="text/javascript">
            function showMessage(message){
                toastr[message.type](message.content, message.title);
            }

            $(function(){
                var systemMessage = @Html.Raw(TempData[MyDialogMvcApp.BaseController.SystemMessage]);               

                showMessage(systemMessage);

                $('#aShowMessage').click(function(){ showMessage(systemMessage) });
            });
        </script>
    </body>
</html>

Browser other questions tagged

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