如何在回发后保持dropdownlist选择值?

时间:2014-11-17 08:43:59

标签: jquery asp.net-mvc asp.net-mvc-4 postback

我是mvc开发的新手,我有4个dropbox,每个dropdown触发下一个dpdown对象来绑定值。

在选择所有下拉列表后绑定gridview(codeplex mvc.grid)并单击我的按钮。

我的问题是:

如何在回发后保存dropdownlist选择的值?

感谢您的帮助

  

查看:

@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)
  

脚本

$(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);
})}});
  

控制器

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));
}

2 个答案:

答案 0 :(得分:2)

您需要使用Html.DropdwonlistFor

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

其中m.ClientID是选定值

答案 1 :(得分:1)

好的,实现这一目标的方法很少。如果可能,我强烈建议您强烈输入您的观点。这使您可以轻松访问已发布的表单数据,而不是通过FormCollection。这也使您能够将Model返回到视图,该视图将自动选择公司下拉列表(我假设默认情况下会填写所有公司,并且不会通过ajax来获取它们)。

所以,回答你的问题。正如您获得dpStartCheckListdpEndCheckList的值一样,也要将其他两个下拉列表的值存储在ViewBag中。现在在您看来,执行以下操作。将viewbags中的值保存到js变量

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

等等。

现在,在每个相应的ajax done回调中,使用$.each将项目添加到下拉列表后,您可以将相应的值设置为下拉列表。例如,如果你拿银行下拉列表。在$.each

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

<强>更新 观看此YouTube视频,它会讨论强类型视图https://www.youtube.com/watch?v=xRinkoUpEEM

更新2 如果您使用此方法,请记住将js变量设置为&#39;&#39;或者在设置后未定义。

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

否则,如果选项中存在该值,它将在未来的ajax调用中从下拉列表中选择相同的值