Search code examples
asp.netasp.net-mvc-5

MVC action returning just viewbag result


I'm new to MVC 5.

I have a page called MyPage.cshtml in the MyController directory. On that page I have a link that is defined as....

@Html.ActionLink("Get Info", "GetInfo", "MyController", new { myId = 1 }, null)

So, in the MyController controller I have a GetInfo method. I just want it to do some stuff, fill in a ViewBag result then return back to the same page it's on, which is MyPage. But I get an 'Object reference not set to an instance of an object.' error when the page is loading. I'm thinking on the redirect to MyPage it's model is lost. Here's my code....

public ActionResult GetInfo(int myId){
  // do stuff
  ViewBag.Result = "this is a test";
  return this.View("MyPage");
}

So, to simplify things: I'm really dealing with ONLY ONE page, MyPage. The link click is just calling a custom method to do some stuff, and I want it to return right back where it was. Any suggestions please?


Solution

  • You are getting this error

    Object reference not set to an instance of an object.

    because your view MyPage depends on a model you are not sending it.

    There are different ways to handle your second issue:

    If you want to show the MyPage after executing the GetInfo action, your going to want to use TempData[""]:

    public ActionResult GetInfo(int myId)
    {
      // do stuff
      TempData["Result"] = "this is a test";
      return RedirectToAction("MyPage");
    }
    

    And then in your MyPage view:

    @TempData["Result"]
    

    Another (less desirable) option is to populate the MyPage's model and return it like you did originally, this does not do a "redirect":

    public ActionResult GetInfo(int myId){
      // do stuff
      ViewBag.Result = "this is a test";
    
      var model = // ... populate model like (or from) MyPage
    
      return View("MyPage", model);
    }