控制器中的变量即使在设置后也会返回null

时间:2015-01-30 16:24:35

标签: c# asp.net-mvc

即使理论上已经设置了控制器中的变量,它也会返回null。我做错了什么?

控制器:

public class HomeController : Controller
{
    List<DataModel.MonthlyCount> table;

    List<DataModel.MonthlyCount> GetTableData(DateTime startDate, DateTime endDate)
    {
        table = DataManager.PopulateList(startDate, endDate);
        return table;
    }

    public ActionResult Monthly()
    {
        return View();
    }
    public PartialViewResult MonthlyTable(String startDate, String endDate)
    {
        DateTime sDate = DateTime.Parse(startDate);
        DateTime eDate = DateTime.Parse(endDate);
        if (table == null)
        {
            table = GetTableData(sDate, eDate);
            Debug.WriteLine("If you see this, it means table was null");
            Debug.WriteLine(table);
        }

        return PartialView("_MonthlyTable", table);
    }
    [HttpPost]
    public ActionResult ExcelExporter(String[] monthlySelections, String startDate, String endDate, String excelExporter)
    {
        DateTime sDate = DateTime.Parse(startDate);
        DateTime eDate = DateTime.Parse(endDate);
        int numMonths = ((sDate.Year - eDate.Year) * 12) + sDate.Month - eDate.Month;          

        if (table == null)
        {
            table = GetTableData(sDate, eDate);
        }
        ModelState.Clear();
        if (excelExporter == "true")
        {
            Workbook workbook = Data.MonthlyExcelExport.MaptoExcelTemplate(table, monthlySelections, numMonths);
            ExcelDownload(workbook, WorkbookFormat.Excel97To2003);
        }
        return View();
    }

查看:

    <form id ="exportForm" name="exportForm" action ="Home/ExcelExporter" method ="post">
    <div class ="date-pick">
        <span>
           Start date <input type="text" id="start_date" name ="startDate" required=""/>
        </span> 
        <span>
            End date <input type="text" id="end_date" name ="endDate" required =""/>
        </span>
        <button type="button" id="updatePage" name="excelExporter" value="false" onclick="return clicked()">Update Page</button>
        <button type="submit" id ="excelExporter" name="excelExporter" value ="true" onclick="return clicked()">Export to Excel</button>
    </form>
<script>
$("#updatePage").click(function () {
    $.ajax({
        type: 'POST',
        datatype: 'html',
        data: $('#exportForm').serialize(),

        url: '../Home/MonthlyTable',
        success: function (data) {
            $('#_MonthlyTable').html(data);
        },
        error: function (data) {
            alert("failed");
        },
    });
});
</script>

我试图制作它,以便我只需要运行一次GetTableData()方法,无论是按下更新页面(ajax调用)按钮还是按下导出到Excel按钮,只进行一次数据库调用。

0 个答案:

没有答案