0

I was trying to let my Html.DropDownList retain some value which user had chosen.

The code was about to use selected value in SelectList to retain value to make the dropdownlist retain the value which user had previously chosen. The page was constructed under MVC. After trying for a while, I found that the web page could only return to its original status (before user chooses anything) but could not retain any dropdownlist value after pressing submit button.

I also used jQuery to control the showing and hiding of multiple dropdownlists which I need only a group dropdownlist to appear and to show another when value is selected (retail,bus,bike,track, etc,... are the values of group dropdownlist and name of additional dropdownlists).

The following is my my code : Controller:

public List<SelectListItem> SetGroup(string group)
        {
            List<SelectListItem> groups = new List<SelectListItem>();
            groups.AddRange(new SelectList(GMManager.FindAllGroup(), "MerchantNo", "MerchantName", group));
            groups.Add(new SelectListItem() { Text = "ALL", Value = "ALL", Selected = false });
            return groups;

        }

        public List<SelectListItem> SetRetail(string retail)
        {
            List<SelectListItem> retails = new List<SelectListItem>();
            retails.AddRange(new SelectList(GMManager.FindAllRetail(), "MerchantNo", "MerchantName",retail));
            retails.Add(new SelectListItem() { Text = "ALL", Value = "ALL", Selected = false });
            return retails;

        }

        public List<SelectListItem> SetBus(string bus)
        {
            List<SelectListItem> buses = new List<SelectListItem>();
            buses.AddRange(new SelectList(GMManager.FindAllBus(), "MerchantNo", "MerchantName",bus));
            buses.Add(new SelectListItem() { Text = "ALL", Value = "ALL", Selected = false });
            return buses;

        }

        public List<SelectListItem> SetBike(string bike)
        {
            List<SelectListItem> bikes = new List<SelectListItem>();
            bikes.AddRange(new SelectList(GMManager.FindAllBike(), "MerchantNo", "MerchantName",bike));
            bikes.Add(new SelectListItem() { Text = "ALL", Value = "ALL", Selected = false });
            return bikes;

        }

        public List<SelectListItem> SetTrack(string track)
        {
            List<SelectListItem> tracks = new List<SelectListItem>();
            tracks.AddRange(new SelectList(GMManager.FindAllTrack(), "MerchantNo", "MerchantName",track));
            tracks.Add(new SelectListItem() { Text = "ALL", Value = "ALL", Selected = false });
            return tracks;

        }

        public List<SelectListItem> SetParking(string parking)
        {
            List<SelectListItem> parkings = new List<SelectListItem>();
            parkings.AddRange(new SelectList(GMManager.FindAllParking(), "MerchantNo", "MerchantName",parking));
            parkings.Add(new SelectListItem() { Text = "ALL", Value = "ALL", Selected = false });
            return parkings;

        }

        public List<SelectListItem> SetOutsourcing(string outsourcing)
        {
            List<SelectListItem> outsourcings = new List<SelectListItem>();
            outsourcings.AddRange(new SelectList(GMManager.FindAllOutsourcing(), "MerchantNo", "MerchantName",outsourcing));
            outsourcings.Add(new SelectListItem() { Text = "ALL", Value = "ALL", Selected = false });
            return outsourcings;

        }  


public ActionResult RPT_160501()
        {
           string start = DateTime.Now.ToString("yyyyMMdd");
            string end = DateTime.Now.ToString("yyyyMMdd");
            string group = "";
            string retail = "";
            string bus = "";
            string bike = "";
            string track = "";
            string parking = "";
            string outsourcing = "";

            DataTable dt = null;



                if (Request.Form["searchConfirm"] != null || Request.Form["ExportExcel"] != null)
                {
                    start = Request.Form["startDate"];
                    end = Request.Form["endDate"];

                    group = Request.Form["group"];
                    retail = Request.Form["retail"];
                    bus = Request.Form["bus"];
                    bike = Request.Form["bike"];
                    track = Request.Form["track"];
                    parking = Request.Form["parking"];
                    outsourcing = Request.Form["outsourcing"];
                }

                ViewBag.Group = SetGroup(group);
                ViewBag.Retail = SetRetail(retail);
                ViewBag.Bus = SetBus(bus);
                ViewBag.Bike = SetBike(bike);
                ViewBag.Track = SetTrack(track);
                ViewBag.Parking = SetParking(parking);
                ViewBag.Outsourcing = SetOutsourcing(outsourcing);

                ViewBag.RepName = "ReportName";
                ViewBag.Start = start;
                ViewBag.End = end;

View:

<script>
    $(document).ready(function () {
        $("#retail").hide();
        $("#bus").hide();
        $("#bike").hide();
        $("#track").hide();
        $("#parking").hide();
        $("#outsourcing").hide();
        $("#group").on("change", function () {
            switch ($(this).val()) {
                case "RETAIL":
                    $("#retail").show();
                    $("#bus").hide();
                    $("#bike").hide();
                    $("#track").hide();
                    $("#parking").hide();
                    $("#outsourcing").hide();
                    break;
                case "BUS":
                    $("#retail").hide();
                    $("#bus").show();
                    $("#bike").hide();
                    $("#track").hide();
                    $("#parking").hide();
                    $("#outsourcing").hide();
                    break;
                case "BIKE":
                    $("#retail").hide();
                    $("#bus").hide();
                    $("#bike").show();
                    $("#track").hide();
                    $("#parking").hide();
                    $("#outsourcing").hide();
                    break;
                case "TRACK":
                    $("#retail").hide();
                    $("#bus").hide();
                    $("#bike").hide();
                    $("#track").show();
                    $("#parking").hide();
                    $("#outsourcing").hide();
                    break;
                case "PARKING_LOT":
                    $("#retail").hide();
                    $("#bus").hide();
                    $("#bike").hide();
                    $("#track").hide();
                    $("#parking").show();
                    $("#outsourcing").hide();
                    break;
                case "BANK_OUTSOURCING":
                    $("#retail").hide();
                    $("#bus").hide();
                    $("#bike").hide();
                    $("#track").hide();
                    $("#parking").hide();
                    $("#outsourcing").show();
                    break;
                default:
                    $("#retail").hide();
                    $("#bus").hide();
                    $("#bike").hide();
                    $("#track").hide();
                    $("#parking").hide();
                    $("#outsourcing").hide();
                    break;
            }
        })
    })

</script>


<meta name="viewport" content="width=device-width" />
<title>@ViewBag.RepName</title>

<h2>@ViewBag.RepName</h2>



@using (Html.BeginForm("RPT_160501", "ReportSystem", FormMethod.Post, new { id = "searchForm" }))
{
    <div>
        <label for="startDate"> Date:</label>
        <input type="text" name="StartDate" id="StartDate" value="@ViewBag.Start" style="width:100px;" /> ~
        <input type="text" name="EndDate" id="EndDate" value="@ViewBag.End" style="width:100px;" />


        @Html.DropDownList("group", (IEnumerable<SelectListItem>)ViewBag.Group, "--Please Choose--")
        @Html.DropDownList("retail", (IEnumerable<SelectListItem>)ViewBag.Retail, "--Please Choose--")
        @Html.DropDownList("bus", (IEnumerable<SelectListItem>)ViewBag.Bus, "--Please Choose--")
        @Html.DropDownList("bike", (IEnumerable<SelectListItem>)ViewBag.Bike, "--Please Choose--")
        @Html.DropDownList("track", (IEnumerable<SelectListItem>)ViewBag.Track, "--Please Choose--")
        @Html.DropDownList("parking", (IEnumerable<SelectListItem>)ViewBag.Parking, "--Please Choose--")
        @Html.DropDownList("outsourcing", (IEnumerable<SelectListItem>)ViewBag.Outsourcing, "--Plase Choose--")

        <input type="submit" name="searchConfirm" value="Search" class="btn btn-default" />
        <input type="submit" name="ExportExcel" value="Export Excel" class="btn btn-default" />
    </div>
}
<table class="grid" width="100%">
    <thead>
        <tr style="background-color: lightgray">
            <th>
                A
            </th>
            <th>
                B
            </th>
            <th>
                C
            </th>
            <th>
                D
            </th>


        </tr>
    </thead>
    <tbody>
Jack
  • 9
  • 2
  • You not correctly binding to anything. Use a view model and strongly bind to it. Refer the code in [this question/answer](http://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of-type-system-int32-but-must-be-o) for how to create you model and bind to it –  Feb 07 '17 at 09:06

1 Answers1

0

You are not using MVC as it is intended. The Action method RPT_160501 should have a strong typed ViewModel object as a parameter, allowing MVC to parse and bind the posted Form values, instead of you doing it all by yourself.
The same applies to the View which also seems to have no @model declaration because ViewBag is used for everything.

While it is parsing and binding, MVC will also fill the global ModelState object which - among many things - is also used internally by MVC to render posted or attempted values, as long as you use Html.DropDownListFor(m => m.group, ....) <-- this is my answer to your question, but it only works if you adopt this approach as a whole.

There are certainly ways to do what you need without a ViewModel, but that would only lead you further down the wrong path. Better to stop here, learn the correct way, and then proceed with much greater ease.

See e.g. this question for more on this: MVC ViewModel example

Community
  • 1
  • 1
Peter B
  • 22,460
  • 5
  • 32
  • 69