You must Sign In to post a response.
  • Category: .NET

    How could I set selected item to session MVC(razor) ?

    I want to set selected item from dropdown to Session in MVC5 ,so that it can be used anywhere in the application for the current user, Kindly let me know is there any other workaround?

    What I have tried:

    @Html.DropDownList("CompanyList", ViewBag.CompanyList as SelectList,
    "Select a Company", new { id = "CompanyId" })



    <input type="button" value="Go" id="btnSelect"
    />
    @section scripts
    {
    <script>
    $("#btnSelect").click(
    function ()
    {
    var value = document.getElementById("CompanyId").value;
    @Context.Session["CompanyId"]="'"+value+"'";
    alert( "Session "+ @Context.Session["CompanyId"].ToString());
    }
    );
    </script>
    }


    but this returns expression being session points to NUll
  • #765263
    Hi,
    Just post to MVC controller and set the Session variable.
    //jQuery code:
    $(function () {
    $.post('/SetVar/SetSessionValue',
    { CompanyId : "abc", value : document.getElementById("CompanyId").value }, function (data)
    {
    alert("Success " + data.success);
    });
    });

    //Controller code:
    public class SetVarController : Controller
    {
    public ActionResult SetSessionValue(string CompanyId, string value)
    {
    Session[CompanyId] = value;
    return this.Json(new { success = true });
    }
    }
    You can find detailed code's over here:
    http://dotnetslackers.com/articles/aspnet/Save-and-retrieve-Session-data-via-Ajax-using-JQuery-in-an-MVC-3-application.aspx
    Hope it helps.
    Regards,
    Shashikant Gurav
    shashikantgurav22@gmail.com


Sign In to post your comments