Persist information using ViewBag?

1

I have my login screen and want to show the name is the 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 you 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>
    
asked by anonymous 28.12.2015 / 18:16

3 answers

2

Since you are going to make a redirect, you have to use TempData itself. 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 throughout the session use Session :

Session["Login"] = retorno.login;
Session["senha"] = retorno.senha;
Session["nome"] = retorno.nomeusuario;
Session["id"] = retorno.idusuario;
    
28.12.2015 / 18:32
2

Controller C #:

ViewBag.Nome = "Jr";

Html:

@ViewBag.Nome
    
28.12.2015 / 18:23
2

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

Using Viewbags or ViewModels?

@bigown's answer solves your 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 at least, not that way from your example.

In this case, it is best to use ViewModels. Take a look at the two replies to 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 strongly typed data.

It would look something 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 run a great risk of form resubmission.

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>

I hope I have helped.

    
12.07.2017 / 00:35