Search code examples
asp.net-mvcdynamiccontrollers

How to pass variables from one controller to another


I would like to pass the variables to the other Controllers TableName, I'm trying to ViewBag.Variable but do send the null.

if you can pass these parameters from one controller to another thank you very much in advance for the help

public class HomeController : Controller
{
    public ActionResult Index()
    {
        string NombreVariable = "TablaUsuario";
        ViewBag.Variable = NombreVariable;
        return View();    
    }



    [ValidateInput(false)]
    public ActionResult GridViewPartial()
    {


        var entity = (IEnumerable)db.GetType()
                       .GetProperty(ViewBag.Variable)
                       .GetValue(db, null);
        var model = entity.Cast<object>();
        return PartialView("_GridViewPartial", model);


    }

  [HttpPost, ValidateInput(false)]

    public ActionResult GridViewPartialAddNew()
    {
        var entity = (dynamic)db.GetType() 
                       .GetProperty(ViewBag.Variable)
                       .GetValue(db, null);
        var model = entity;

        if (ModelState.IsValid)
        {

            try
            {
                Model.TableUsuario tb = new Model.TableUsuario();

                int contador=tb.GetType().GetProperties().Count();
                 //Coleccion[] cual = new Coleccion[contador];
                 int contadores = 0;
                string[] valores = new string[contador];

                foreach( var i in tb.GetType().GetProperties())
                {

                    valores[contadores] = "'" + Convert.ToString(GridViewExtension.GetEditValue<dynamic>(i.Name)) + "' AS " + i.Name ;


                    contadores += 1;

                }
                db.Database.ExecuteSqlCommand("insert into TableUsuario SELECT " + string.Join(",",valores));
                db.SaveChanges();
            }
            catch (Exception e)
            {
                ViewData["EditError"] = e.Message;
            }
        }
        else
            ViewData["EditError"] = "Please, correct all errors.";
        return PartialView("_GridViewPartial", model);
    }

Solution

  • If you want to call method_A in Controller_A, from Controller_B, you can do it like this:

    In Controller_B

    Controller_A myControllerA = new Controller_A();
    myControllerA.method_A(myVariable);
    

    In Controller_A

    public void method_A(MyClass myVariable)
    ...
    ...
    

    Alternatively, if you want a "global" variable that is available everywhere, you can assign it to Session, in a similar way you use ViewBag

    Session["myVariable"] = myVariable;
    

    Though I would caution against using session: not everything belongs in the session state.

    I guess it depends on exactly what you want to achieve.