Save data to a Viewbag

Asked

Viewed 761 times

2

I am developing an application, where I have a Viewbag listing a list of numbers, from my database.

I need to write the selected number in this dropdown, in another Viewbag. I don’t know how to do this, someone could help me?

Viewbag returning the list of numbers:

ViewBag.Contrato = usuarioRepository.Lista.Where(u => u.sLogin == autenticacaoProvider.UsuarioAutenticado.Login).Select(u => u.SqContrato);

View with the Dropdownlist:

@Html.DropDownList("Contrato", new SelectList(ViewBag.Contrato, "Contrato"))

There is some syntax, like "@Html.Dropdownlistfor(@Viewbag)"?

  • Ih ai ok? The functioning of the forum here is a little different from other forums. When requesting some post information use the option Comment on. In this case answers would only be the answers to the post. View http://answall.com/tour. for more information and familiarize yourself. And welcome to the community.

  • Sorry for the lack of knowledge. From now on, I will use the forum correctly.

  • I also made a lot of mess at first. I’m Jothaz you remember?

2 answers

3

Hello,

On the controller do

  public ActionResult Index(){
    dynamic model = new System.Dynamic.ExpandoObject();
    model.Lista =  usuarioRepository.Lista.Where(u => u.sLogin == autenticacaoProvider.UsuarioAutenticado.Login).Select(u => u.SqContrato);

return View(model);
}

And in the view just call

@Model.Lista

to access the list, to make a Dropdownbox, has a mode that is at hand.

<select>
@foreach(var item in Model.Lista){
 <option value="item.valor">item.texto</option>
}
</select>

I’m sorry if you have any syntax error, I did everything here without playing in the visual studio.

  • Even this part, I had already managed to arrive. I now need the user to choose an option, and I can save this option in some type of global variable( Viembag, Viewmodel, or something like), so I can use in a query.

  • Ask another question and explain putting code please.

  • I re-asked the question by explaining my scenario. http://answall.com/questions/46382/salvar-dados-em-umaviari%C3%A1vel-global

  • If this answer here helped you, mark it as correct.

2


Alternatively to @Paulohdsouza’s reply, no need to use ExpandoObject to return a database object. C# dynamic inference already solves this problem:

public ActionResult Index()
{
    var lista =  usuarioRepository.Lista.Where(u => u.sLogin == autenticacaoProvider.UsuarioAutenticado.Login).Select(u => u.SqContrato);

    return View(lista);
}

Obviously, you need to set up @model at the beginning of View:

@model IEnumerable<Usuario>
  • Interesting, I didn’t know this way. + 1

Browser other questions tagged

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