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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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); }
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0