Viewbag是否返回null?

时间:2020-05-21 18:05:17

标签: c# ajax model-view-controller

我遇到错误:无法对空引用执行运行时绑定。

尝试通过ajax调用发回到我的控件时出现错误。

$('#main-content-submit').click(function () {
        var labelArray = [];
        labelArray = $("input:checkbox[name=type]:checked").map(function () {
            return $(this).closest('label').text();
        }).get();
        console.log(labelArray);
        event.preventDefault();

        //Ajax call to get all months and years
        $.ajax({
            type: 'POST',
            url: '/Home/Extract',
            data: JSON.stringify({ name: labelArray}),
            contentType: 'application/json',
            success: function (_result) {

            },
            error: function (err, _result) {
                alert("Error in Extract" + err.responseText);
            }
        });

        return false;
    });



> Here is my view: I am getting the error and it is highlighting my @ViewBag.StatementYears items.
<div class="form-group">
            <label class="year" for="Year">Step 2 - Select Statement Year(s) :</label>

            <div id="checkboxes" class="grid-container2">
                <label><input class="year" type="checkbox" name="type" id="chkBoxYear_1"> @ViewBag.StatementYears[0]</label>
                <label><input class="year" type="checkbox" name="type" id="chkBoxYear_2"> @ViewBag.StatementYears[1]</label>
                <label><input class="year" type="checkbox" name="type" id="chkBoxYear_3"> @ViewBag.StatementYears[2]</label>
                <label><input class="year" type="checkbox" name="type" id="chkBoxYear_4"> @ViewBag.StatementYears[3]</label>
                <label><input class="year" type="checkbox" name="type" id="chkBoxYear_5"> @ViewBag.StatementYears[4]</label>
                <label><input class="year" type="checkbox" name="type" id="chkBoxYear_6"> @ViewBag.StatementYears[5]</label>
                <label><input class="year" type="checkbox" name="type" id="chkBoxYear_7"> @ViewBag.StatementYears[6]</label>
                <label><input class="year" type="checkbox" name="type" id="chkBoxYear_8"> @ViewBag.StatementYears[7]</label>
                <label><input class="year" type="checkbox" name="type" id="chkBoxYear_9"> @ViewBag.StatementYears[8]</label>
            </div>
            <button id="selection" class="select-all-years">Select All Years</button>

        </div>

这是我的控制器

[HttpPost]
    public ActionResult Extract(string[] name)
    {

        return View("Index");
    }

1 个答案:

答案 0 :(得分:0)

您的 @ ViewBag.StatementYears 似乎是在 Index 控制器中定义的,而不是在 Extract 控制器中定义的。您试图返回一个视图而不定义其ViewBag。我可以为您提供2种解决方案:

  1. 提取控制器中定义 @ ViewBag.StatementYears
  2. 在您的 Extract 控制器中使用return RedirectToAction("Index")代替return View("Index")