how to pass data from a controller to a view that is not yours?

4

For example I have the DeleteUsers driver whose view is DeleteUsers.cshtml and another where the driver is Users and the view is Users.cshtml what I want is to pass the value of ViewBag.Error in DeleteUsers (controller) to Users (Vista) for there to be able to show the error

namespace Sistema.Controllers
{
    public class Usuarios : Controller
    {
        public ActionResult Usuarios()
        {
            return(db.Usuarios.Tolist())
        }

        public ActionResult EliminarUsuario
        {
            // ?????????????????aquí regresar a la vista                 
            // Usuarios con el valor de  ViewBag.Error
        }
    }
}


/////////////Vista Usuarios
@model IEnumerable<Sistema.Models.Usuario>
@{ 
    ViewBag.Title = "Usuarios";
}
///Recibir valor de ViewBabag
@ViewBag.Error
    
asked by Xique 18.08.2016 в 19:16
source

2 answers

4

Your class should be called UsuariosController instead of Usuarios

namespace Sistema.Controllers
{
    public class Usuarios : Controller
    {
      public ActionResult Usuarios()
        {
         ViewBag.Error = TempData["Error"];
         return(db.Usuarios.Tolist());
        }
      public ActionResult EliminarUsuario()
        {           
        TempData.Add("Error", "El detalle del error");
        return RedirectToAction("Usuarios"); 
        }
    }
}

/////////////Vista Usuarios
@model IEnumerable<Sistema.Models.Usuario>
@{ 
    ViewBag.Title = "Usuarios";
}
///Recibir valor de ViewBabag
@ViewBag.Error

As you are just starting with ASP.net MVC , I recommend you visit the following workshop that I did the previous month: link

    
answered by 18.08.2016 / 19:27
source
2

You have two options:

1) Return a RedirectToAction, which will execute the code of the Action that you call:

public ActionResult EliminarUsuario()
{
    return RedirectToAction("Usuarios");
}

2) Return directly a View different from the one corresponding to Action , passing its name (Returns the View without going through the Action Usuarios ):

public ActionResult EliminarUsuario()
{
    return View("Usuarios");
}
    
answered by 18.08.2016 в 20:18