Haminteu
Haminteu

Reputation: 1334

Jquery Select load back after refresh page

Well, It's a simple one and I know there are a lot of source about this thing.
I've a jquery script like:

<script>
    $(document).ready(function () {
        $("#CountryId").change(function () {
            $.get("@Url.Action("GetStateList","Controllers1")", { sOId: $("#CountryId").val() }, function (data) {
                $("#StateId").empty();
                $.each(data, function (index, row) {
                    $("#StateId").append("<option value='" + row.PersonnelNumber + "'>" + row.Name + "</option>")
                });
            });
        })
    });
</script>

public JsonResult GetStateList(string sOId)
    {
        string sPositionNumber = Session["xPersonnelNumber"].ToString();

        db.Configuration.ProxyCreationEnabled = false;
        List<Employee> StateList = db.Employees.Where(x => x.OrganizationNumber == sOId && x.Name != null).OrderBy(o => o.Name).ToList();
        return Json(StateList, JsonRequestBehavior.AllowGet);
    }

After the page refresh, the StateId option is empty. How can I keep the option list after the page is refresh? If I remove the .Empty(), it will append another option. It's cascading dropdown using MVC .NET

Really appreciated.

Upvotes: 0

Views: 118

Answers (2)

Jon Ryan
Jon Ryan

Reputation: 1627

HTTP is stateless. There are however ways to persist data in ASP.NET MVC:

  • Hidden Field
  • Cookies
  • Query String
  • ViewData
  • ViewBag
  • TempData

Good article:

https://www.c-sharpcorner.com/article/state-management-in-asp-net-mvc

However most of these methods require you to post the data to the controller, and as such data will get lost on refresh.

So viable options are...

Option 1: Caching

You could use a simple memory cache to store the list against a custom identifier, such as the user ID for a period of time, and update it every time the GetStateList method is called. Populating the initial list on page load from the cache.

Option 2: Browser side persistence

You could look at browser side persistence of data and look into things like:

Upvotes: 0

SYED
SYED

Reputation: 26

Your problem in your country options it is been selected first option automatically while you refresh, so you can set your desire country for the states in page loading.

<script>
    $(document).ready(function () {

        **$('#CountryId').val('desire country');**

        $("#CountryId").change(function () {
            $.get("@Url.Action("GetStateList","Controllers1")", { sOId: $("#CountryId").val() }, function (data) {
                $("#StateId").empty();
                $.each(data, function (index, row) {
                    $("#StateId").append("<option value='" + row.PersonnelNumber + "'>" + row.Name + "</option>")
                });
            });
        })
    });
</script>

Upvotes: 1

Related Questions