Related Tags:
Asp.Net It was developed by Microsoft to allow programmers to build dynamic web sites, web applications and web services. It was first released in January 2002 with version 1.0 of the .NET Framework, and is the successor to Microsoft's Active Server Pages (ASP) technology. Learn More, C# C# (pronounced "C-sharp") is an object-oriented programming language from Microsoft that aims to combine the computing power of C++ with the programming ease of Visual Basic. C# is based on C++ and contains features similar to those of Java. Learn More, ASP.NET MVC The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NET features, such as master pages and membership-based authentication. The MVC framework is defined in the System.Web.Mvc assembly. Learn More,

Viewbag variable always getting null value while accessing it in view, while using RedirectToAction to call the redirection

Description:How to set Viewbag before making a redirection call?
or need to know if there is a mistake in Displaying ViewBag after RedirectToAction ?
I have set the value of my viewbag variable in the controller method then use the RedirectToAction method for the redirection but when trying to use the value of the variable in my view that is always returning null value.I have use following code in my controller method.


public ActionResult Index1 () {
//some code logic placed here
ViewBag.Myvariable = "Some value";
return RedirectToAction("Home");
}

Posted by: | Posted on: Jul 16, 2018

1 answers

Replies

3

Hi,
Actually you are using "RedirectToAction" method which redirect you to another action "Home" in your case. In MVC to pass data between controller methods you need to use the TempData variables and for passing data from controller method to view you can use viewbag. So in your case what you are trying to achieve can be achieved by using the following code.

public ActionResult Index1 () {
//some code logic placed here
TempData["Myvariable"] = "Some value";
return RedirectToAction("Home");
}

public ActionResult Home () {
//now you can use ViewBag (if I want to)by using TempData["Myvariable"] to fill the content to ViewBag.Myvariable
//some code logic placed here
ViewBag.Myvariable = Convert.ToString(TempData["Myvariable"]);
return View();
}

To get more clarity you can read the the difference between ViewData,ViewBag and TempData

Replied by: | Replied on: Jul 17, 2018



Reply