Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
Hello;
How can I store a selected value in a drop down list (ASP.NET/MVC) within a session variable after the onchange event?
My code in ascx
HTML
<table width="150" border="0" cellspacing="0" cellpadding="0" style="margin-removed 1px; margin-removed 1px; margin-removed 1px;">
    <tr>       
        <td class="formrechinp">
            <%= Html.DropDownList("localSite",
                                          SiteHelper.GetSitesList((CultureInfo) Session["Culture"],
                                                                  menuState.Site_Name),
                                          new
                                              {
                                                  onChange = "javascript:ChangeLocalSite(this.value);"
                                              }) %>         
        </td>
    </tr>
</table>


My code in cs:
C#
public void ChangeLocalSite(String value)
       {
           Session["localSite"] = value;
       }
Posted

1 solution

ChangeLocalSite is javascript method and it is available only on "that" html page. But the Session["localSite"] is in the (web)server.

To set Session variable you may have to execute a server method from javascript. This only possible way of doing this through ajax call. Donot be scared of ajax. It is very easy to learn and use an ajax method.

here is an example using jquery:


C#
   public void ChangeLocalSite(String value)
        {
            
         $.ajax({
          url: "MyMethod",
          dataType: 'json',
          type: 'POST',
          data:value,
          success: function (data) {
          if (data != null)
           alert(data);//should display found it!
          }
          }
         });
        }


//this is method is in YourController.cs
[HttpPost]
string MyMethod(string value)
{
    Session["localSite"] = value;
    return "found it!";
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900