Persist information using ViewBag?

I have my screen login is I want to show the name is user id logged on another screen, so I can use this information.

In my controller :

[HttpPost]
    public ActionResult Index(TB_USUARIO model)
    {

            //aqui vai pesquisar o login é senha
            try
            {
                var tbuscar = new UsuarioAplicacao();
                var retorno = tbuscar.ListarPorLoginSenha(model.login, model.senha);

                if (retorno != null)
                {

                    ViewBag.Login = retorno.login;
                    ViewBag.senha = retorno.senha;
                    ViewBag.nome = retorno.nomeusuario;
                    ViewBag.id = retorno.idusuario;
                    return RedirectToAction("index", "MenuPrincipal");
                }
                else
                {
                    TempData["Erro"] = "Usuário não localizado.";
                }

                ModelState.Clear();
            }
            catch (Exception ex)
            {
                TempData["Erro"] = ex.Message;
            }

            return View();
        }


}

I want to show this information:

@{
    ViewBag.Title = "Index";
}

@section menu{
    <!-- NAVBAR
    ================================================== -->

<nav class="navbar navbar-inverse navbar-fixed-top">
    <div class="container-fluid">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">opciones de menú</a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li><a href="/Home"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
            </ul>

        </div><!--/.nav-collapse -->
    </div><!--/.container-fluid -->
</nav>


  <!-- NAVBAR FIM
  ================================================== -->

}


    <br/>

    <div class="panel panel-default">
        <div class="panel-heading">Controle: @TempData["id"]</div>
        <div class="panel-heading">Nome: @TempData["nome"] </div>
    </div>
Author: Maniero, 2015-12-28

3 answers

Since you are going to do a redirect, you have to use the same TempData. ViewBag does not survive in this scenario.

TempData["Login"] = retorno.login;
TempData["senha"] = retorno.senha;
TempData["nome"] = retorno.nomeusuario;
TempData["id"] = retorno.idusuario;

Reference .

If you want to keep the information for the entire session use Session:

Session["Login"] = retorno.login;
Session["senha"] = retorno.senha;
Session["nome"] = retorno.nomeusuario;
Session["id"] = retorno.idusuario;

I put on GitHub for future reference .

 4
Author: Maniero, 2019-11-12 14:39:22

I was researching about viewbags and ended up finding this question, but my question was:

Use viewbags or viewmodels ?

@Maniero's answer solves his problem with the basic concept of the difference between Viewbag, Viewdata and Tempdata.

However, I answer your question differently:

Persist information using ViewBag ?

No! or by less, not that way of your example.

In this case, the ideal is to use viewmodels. Take a look at the two answers in this post ViewModels or ViewBags.

In this way you would create an encapsulated class of your Login and in your view you would receive a template and use the data strongly typed.

Would be more or less like this:

LoginViewModel.cs

public class LoginViewModel
{
    [Display(Name = "Login")]
    [Required(ErrorMessage = "O campo 'login' é obrigatório.")]
    public string login { get; set; }

    [Display(Name = "Senha")]
    [Required(ErrorMessage = "O campo 'senha' é obrigatório.")]
    public string senha { get; set; }
}

LoginController

    public ActionResult Login()
    {
        LoginViewModel login = new LoginViewModel();

        return View(login);
    }

    [HttpPost]
    public ActionResult Login([Bind(Include = "login,senha")] LoginViewModel login)
    {
        LoginViewModel login = new LoginViewModel();

        if (ModelState.IsValid)
        {
            db.TbLogin.Add(login);
            db.SaveChanges();                
        }
        return RedirectToAction("Index");
    }

* Remember: never do

return View();

In a Post method or you will take a big risk of resending forms.

Login.cshtml

 @model LoginViewModel

    @{
        ViewBag.Title = "Entrar";
        Layout = null;
    }

    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.login)
        </dt>

        <dd>
            @Html.TextBoxFor(model => model.login)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.senha)
        </dt>

        <dd>
            @Html.TextBoxFor(model => model.senha)
        </dd>    
    </dl>
 3
Author: Lucas, 2019-09-02 21:08:02

C # Controller:

ViewBag.Nome = "Jr";

Html:

@ViewBag.Nome
 2
Author: Junior S., 2015-12-28 17:23:16