Mennan
Mennan

Reputation: 4497

How to keep dropdownlist selected value after postback?

I m new in mvc development, i have 4 dropboxes and each dropdown triggers next dpdown object to bind values.

I bind gridview(codeplex mvc.grid) after all dropdownlist selected and click my button.

My question is :

How to save dropdownlist selected value after postback ?

Thanks for your helping

View:

@using (Html.BeginForm("Checklist", "Home"))
{`
<div>Dp1</div>
@Html.DropDownList("dpCompany", ViewBag.CompanyList as List<SelectListItem>, new { @class = "btn btn-default dropdown-toggle" })

<div>Dp2</div>
@Html.DropDownList("dpBank", ViewBag.CompanyList as List<SelectListItem>, new { @class = "btn btn-default dropdown-toggle" })

<div>Dp3</div>
@Html.DropDownList("dpStartCheckList", ViewBag.CompanyList as List<SelectListItem>, new { @class = "btn btn-default dropdown-toggle" })

<div>>Dp4</div>
@Html.DropDownList("dpEndCheckList", ViewBag.CompanyList as List<SelectListItem>, new { @class = "btn btn-default dropdown-toggle" })`

  <input type="submit" name="CheckList" value="DO" class="btn btn-default" />

}

  @Html.Grid(Model).Columns(columns =>
  {
     columns.Add(c => c.customer_reference).Titled("Çek No").SetWidth(30);
     columns.Add(c => c.unvan).Titled("Ünvan").SetWidth(30);
     columns.Add(c => c.vergi_no).Titled("Vergi No").SetWidth(30);
     columns.Add(c => c.islem_tarihi).Titled("İşlem Tarihi").SetWidth(30).Format("{0:dd/MM/yyyy}");
     columns.Add(c => c.currency).Titled("Para Birimi").SetWidth(30);
     columns.Add(c => c.full_curr_amount).Titled("Tutar").SetWidth(30).Format("{0:C}").Css("align-right");
  }).WithPaging(10)

Script

$(function () {


                // Company
                $('#dpCompany').on('change', function () {
                    var stateDropdown = $('#dpBank');
                    //disable state drop down
                    stateDropdown.prop('disabled', 'disabled');
                    //clear drop down of old states
                    stateDropdown.empty();

                    //retrieve selected country
                    var company = $(this).val();
                    if (company.length > 0) {
                        // retrieve data using a Url.Action() to construct url
                        $.getJSON('@Url.Action("GetBankList")', {
                        company: company
                    })
.done(function (data) {
    //re-enable state drop down
    stateDropdown.removeAttr('disabled');
    //for each returned state
    $.each(data, function (i, state) {
        var values = state.split('|');
        //Create new option
        var option = $('<option value="' + values[0] + '" />').html(values[1]);
        //append state states drop down
        stateDropdown.append(option);
    });

    //if count 1 bind
    if ($("#dpBank option").length == 1) {
        $("#dpBank").trigger("change");
    }
})
.fail(function (jqxhr, textStatus, error) {
    var err = textStatus + ", " + error;
    console.log("Request Failed: " + err);
});} });
                //
                $('#dpBank').on('change', function () {
                    var stateDropdown = $('#dpCheckStart');
                    //disable state drop down
                    stateDropdown.prop('disabled', 'disabled');
                    //clear drop down of old states
                    stateDropdown.empty();

                    //retrieve selected country
                    var bank = $(this).val();

                    var company = $("#dpCompany").val();
                    if (company.length > 0) {
                        // retrieve data using a Url.Action() to construct url
                        $.getJSON('@Url.Action("GetCheckList")', {
                        companyCode: company,
                        bankCode: bank
                    })
.done(function (data) {
    //re-enable state drop down
    stateDropdown.removeAttr('disabled');
    //for each returned state
    $.each(data, function (i, state) {
        var values = state.split('|');
        //Create new option
        var option = $('<option value="' + values[0] + '" />').html(values[1]);
        //append state states drop down
        stateDropdown.append(option);
    });

    //if count 1 bind
    if ($("#dpBank option").length == 1) {
        $("#dpCheckStart").trigger("change");
    }


})
.fail(function (jqxhr, textStatus, error) {
    var err = textStatus + ", " + error;
    console.log("Request Failed: " + err);
}) } });


                $('#dpCheckStart').on('change', function () {
                    var stateDropdown = $('#dpCheckEnd');
                    //disable state drop down
                    stateDropdown.prop('disabled', 'disabled');
                    //clear drop down of old states
                    stateDropdown.empty();

                    //retrieve selected country
                    var startOver = $(this).val();
                    if (startOver.length > 0) {
                        // retrieve data using a Url.Action() to construct url
                        $.getJSON('@Url.Action("GetListOver")', {
                        startOver: startOver
                    })
.done(function (data) {
    //re-enable state drop down
    stateDropdown.removeAttr('disabled');
    //for each returned state
    $.each(data, function (i, state) {
        var values = state.split('|');
        //Create new option
        var option = $('<option value="' + values[0] + '" />').html(values[1]);
        //append state states drop down
        stateDropdown.append(option);
    })

})
.fail(function (jqxhr, textStatus, error) {
    var err = textStatus + ", " + error;
    console.log("Request Failed: " + err);
})}});

Controller

public ActionResult Index()
{

    ViewBag.Message = "";

    LoadDefaults();

    ViewBag.Loaded = false;
    return View();

}

private void LoadDefaults()
{
    ViewBag.BaseList = new List<SelectListItem>();
    ViewBag.CompanyList = new List<SelectListItem>();
    ViewBag.BankList = new List<SelectListItem>();
    ViewBag.AmountTotalTable = new Dictionary<string, string>();
}

[Authorize]
public ActionResult CheckList(FormCollection form)
{
    ViewBag.Message = "";

    ViewBag.StartSelectedItem = StartCheckNo = form["dpStartCheckList"];
    ViewBag.EndSelectedItem = EndCheckNo = form["dpEndCheckList"];


    F8BaseDB.DbSchema.F8BaseSchema.CheckList chk = new F8BaseDB.DbSchema.F8BaseSchema.CheckList();

    LoadDefaults();


    return View("Index", chk.GetAll(ViewBag.StartSelectedItem, ViewBag.EndSelectedItem));
}

Upvotes: 1

Views: 9522

Answers (2)

Amila
Amila

Reputation: 3816

Okay, There are few ways to achieve this. If it's possible, I strongly suggest that you strongly type your view. This will enable you to access the posted form data easily rather than going through the FormCollection. This will also enable you to return the Model back to the view which will automatically select the company dropdown (which I assume is filled by default with all the companies and doesn't go through ajax to get them).

So, to answer your question. As like you get the values of dpStartCheckList and dpEndCheckList, store the values of the other two dropdowns as well in ViewBag. now in your view, do the following. save the values from viewbags to js variables

var selectedCompany = '@ViewBag.SelectedCompany'
var selectedBank = '@ViewBag.SelectedBank'
var startSelectedItem = '@ViewBag.StartSelectedItem'

and so on.

Now in each of the respective ajax done callbacks, after you add the items to the dropdownlist using $.each you set the respective value to the dropdown. for example, if you take the bank dropdown. after the $.each

$("#dpBank").val(selectedBank);

UPDATE watch this youtube video, it talks about strongly typed views https://www.youtube.com/watch?v=xRinkoUpEEM

UPDATE 2 if you use this method, please remember to set the js variables to '' or undefined once you set it.

$("#dpBank").val(selectedBank);
selectedBank = '';

Otherwise it will select the same values from the dropdown in future ajax calls if that value is present in the options

Upvotes: 1

Debajit Mukhopadhyay
Debajit Mukhopadhyay

Reputation: 4182

You need to use Html.DropdwonlistFor

@Html.DropDownListFor(m => m.ClientID, new SelectList(Model.Clients, "ID", "ClientName"), new { @class = "form-control" })

where m.ClientID is the selected value

Upvotes: 2

Related Questions