Passing array to view using MVC query string
I have multiple roles and I need to transfer these roles to another view using the Return RedirectTo Action method,
My code
string[] roles = new string[] { "Admin", "Supervisor", "Interviewer" };
if (roles.Count() > 1)
{
return RedirectToAction("LoginAs","Admin",new{@roles = roles});
}
When I go through as shown in the LoginAs view I like the Url,
http://localhost:33883/Admin/LoginAs?roles=System.String[]
But no values passed.
+3
source to share
1 answer
Option 1:
public ActionResult Index()
{
string[] roles = new string[] { "Admin", "Supervisor", "Interviewer" };
var routeParameters = new RouteValueDictionary();
for (int i = 0; i < roles.Length; i++)
{
routeParameters["roles[" + i + "]"] = roles[i];
}
return RedirectToAction("Test", "Student", routeParameters);
}
public ActionResult Test(string[] roles)
{
return View("Index");
}
Output -
Option 2:
UseTempData
public ActionResult Index()
{
string[] roles = new string[] { "Admin", "Supervisor", "Interviewer" };
TempData["data"] = roles;
return RedirectToAction("Test", "Student");
}
public ActionResult Test()
{
string[] roles = (string[])TempData["data"];
return View("Index");
}
Output -
Option 3:
UseSession
public ActionResult Index()
{
string[] roles = new string[] { "Admin", "Supervisor", "Interviewer" };
Session["data"] = roles;
return RedirectToAction("Test", "Student");
}
public ActionResult Test()
{
string[] roles = (string[])Session["data"];
return View("Index");
}
Output -
+6
source to share