简体   繁体   中英

Does Viewbag return null?

I am getting error: Cannot perform runtime binding on null reference.

Im getting the error trying to post back to my controll through an ajax call.

 $('#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>

Here is my Controller

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

        return View("Index");
    }

It seems like your @ViewBag.StatementYears is defined in Index controller, but not in Extract controller. You are trying to return a view without defining its ViewBag. I can suggest 2 solutions for you:

  1. Define @ViewBag.StatementYears in Extract controller
  2. Use return RedirectToAction("Index") instead of return View("Index") in your Extract controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM