Save data in a ViewBag

2

I'm developing an application, where I have a ViewBag listing a list of numbers, from my database.

I need to save the selected number in this dropdown, in another ViewBag. I do not know how to do this, could anyone 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 DropDownList:

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

Is there any syntax, such as "@Html.DropDownListFor (@ViewBag)"?

    
asked by anonymous 09.01.2015 / 14:15

2 answers

2

As an alternative to the @PauloHDSouza response, you do not have to use ExpandoObject to return an object from the database. The dynamic inference of C # 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 @model at the beginning of View:

@model IEnumerable<Usuario>
    
09.01.2015 / 19:48
3

Hello,

No controller to 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 way 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 errors, I did everything here without playing visual studio.

    
09.01.2015 / 15:27