Save data in a "Global Variant"

3

Hello, I have a DropDownList, coming from a ViewBag, and I need to write this value to some kind of "global variable". I researched and saw that the best ways to do this are by writing to a ViewBag or a ViewModel.

Scenario: When the user logs on to the system, he will have to choose which contract he wants to access (in a DropDownList). I need this value to be saved, and I can use it in a query soon after, to show data only from this contract. The login is working properly, and I was able to list the contracts in a DropDownList, coming from a viewbag. I just need to get this selected value and use it in another query.

DropDownList code:

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

View calling DropDownList:

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

I'm having difficulty creating the method in the controller that will save this flaw, so I can use it again.

If you need more code, just comment, that post here.

    
asked by anonymous 09.01.2015 / 18:03

2 answers

2

In your form's post (it can be GET yes), you can treat the code in your controller as follows:

public class ContaController : Controller
{
  [HttpPost]
  public ActionResult SelecionarContrato(int Contrato)
  {
        Session["contrato"] = model.Contrato;
        //Some code here...
        return RedirectToAction("Index");
  }

 public ActionResult VerificarContrato()
 {
      var contrato = (int)Session["contrato"];

 }
}

The VerificarContrato method is an example of information retrieval. After putting it in session , make sure the object is null and correct. In the example is an integer, but you can store complex objects as well.

    
09.01.2015 / 18:52
2

Make an assignment to Session on your Controller:

public ActionResult Exemplo(int Contrato) {
    HttpContext.Current.Session["Contrato"] = Contrato;

    ...
}

Retrieving the value:

public ActionResult OutroExemplo() {
     var Contrato = (int)HttpContext.Current.Session["Contrato"];

    ...
}

This, however, is not the best approach for classic load balancing problems. The best approach involves implementing your own session manager , but this is more complicated. Start by making the first approach that is simpler.

    
09.01.2015 / 18:13