发布到控制器后保留下拉列表选择的值

时间:2015-08-28 09:44:03

标签: jquery asp.net-mvc dropdownlistfor

我在视图中有下拉列表,并使用控制器中的值加载此下拉列表。在更改事件时,我需要将数据传递给控制器​​,之后下载列表会重新加载。但我希望在发布到控制器后保留所选值。我的jQuery如下:

$.ajax({ 
        url: "/TimesheetModels/GetUsersForTimesheet",
        type: "Get", 
        success: function (data) {
            for (var i = 0; i < data.length; i++) {                
                opt =  new Option(data[i].First_Name, data[i].EmpId);
                $('#ddlUsers').append(opt); //Load drodown list while page load
            } 
        } 
    });

 $('#ddlUsers').change(function () {
        alert($(this).val());
        var empId = $(this).val();
        startDate = $('#calendar').fullCalendar('getDate').startOf('week');
        window.location.href = "/TimesheetModels/TimesheetApproval?selectDate=" + convertDate(startDate) + "&empId=" + empId; //Pass data to controller
        alert(empId); // i get this alert before pass to controller
         $('#ddlUsers').val(empId);
    });

在控制器中我有这个功能,

 public ActionResult TimesheetApproval(string SelectDate,string empId)
        {
            DateTime startDate;
            if (!DateTime.TryParse(SelectDate, out startDate))
                startDate = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek);

            int EmpId;
            if (empId != null)
                EmpId = Convert.ToInt32(empId);
            else
            {
                 EmpId = Convert.ToInt32(Session["EmpId"].ToString());
            }

            string startDateCalendar = Convert.ToString(startDate.ToString("ddd MMM dd yyyy HH:mm:ss")) + " GMT+0530";
            ViewData["startDateCalendar"] = startDateCalendar;

            DateTime endDate = startDate.AddDays(6);


            List<TimesheetMatrix> _timesheetList = _timesheetDetailViewModel.GetAllProjectTasks(startDate, endDate, EmpId);


            return View(_timesheetList);
        }

任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

您应该在更改下拉列表时执行ajax发布,如下所示: -

 $('#ddlUsers').change(function () {
        alert($(this).val());
        var empId = $(this).val();
        startDate = $('#calendar').fullCalendar('getDate').startOf('week');

   $.ajax({ 
        url: "/TimesheetModels/TimesheetApproval?selectDate=" + convertDate(startDate) + "&empId=" + empId,
        type: "Get", 
        success: function (data) {
            //Any logic
        } 
    });

        alert(empId); // i get this alert before pass to controller
         $('#ddlUsers').val(empId);
    });

通过这种方式,您可以保留下拉列表。