Persist information using Viewbag?

Asked

Viewed 4,226 times

3

I have my screen login is to show the name is id of the logged in user 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>
  • And what is the doubt?

  • <div class="panel-Heading">Control:@Viewbag.name</div> is empty

  • @bigown, I didn’t know I could vote, but I appreciate the reminder!

  • 1

    You can vote for anything you think is cool on the site. And there’s a lot of cool stuff to vote for :)

3 answers

4


If you’re going to redirect, you have to use the TempData same. The 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 information throughout the session use Session:

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

I put in the Github for future reference.

  • your answer was perfect! thank you!

3

I was researching about Viewbags and I ended up finding that question, but my question was:

Utilise Viewbags or Viewmodels?

The @Maniero response 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?

Not! Or at least, not in that way of your example.

In this case, the ideal is to use Viewmodels. Take a look at these two answers post Viewmodels or Viewbags.

This way you would create a class encapsulated in your Login and in your view you would receive a model and use the data strongly typed.

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 it

return View();

in a Post method or you will run a great risk of submitting 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>

2

Controller C#:

ViewBag.Nome = "Jr";

Html:

@ViewBag.Nome

  • <div class="panel-Heading">Control:@Viewbag.name</div> is empty

Browser other questions tagged

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