@ Html.Action in _Shared error while sending a ViewModel by Controller

1

In my _Shared I have a PartialView call _rodape.cshtml but now it will need to receive a ViewModel Since I do not want to create an Action on each Controller , I thought about creating a Controller named _Rodape , and all others Controller inherit from this:

It even ran, but I can not send my ViewModel .

How it was: _Shared

@{Html.RenderAction("_Rodape"); }

HomeController

namespace WmbMVC.Controllers
{
    [VerificarSkin]
    public class HomeController : RodapeController
    {
        private readonly WMBContext db = new WMBContext();

        public ActionResult Index()
        {

RodapeController:

   public class RodapeController : Controller
    {

        public PartialViewResult _Rodape()
        {
            using (WMBContext db = new WMBContext())
            {
                var cliente = db.Clientes.Find(IDC);

                var rodapeVM = new RodapeViewModel
                {
                    Cliente = cliente
                };



                return PartialView("_skin300/_rodape");
            }
        }
    }

When in _rodape.cshtml I try to use @Model.AlgumaCoisa it gives the error:

  

System.NullReferenceException:

I thought of sending direct from _shared o ViewModel to Partial , something like:

   @{Html.RenderAction("_Rodape", new RodapeViewModel()); }

But I need a controller to run a variety of business logic. How to send the ViewModel to a PartialView within a Shared     

asked by anonymous 18.07.2016 / 14:32

1 answer

0

The correct way to do this is to make a derivation of Controller , like this:

public class Controller : System.Web.Mvc.Controller
{

    public PartialViewResult Rodape()
    {
        using (WMBContext db = new WMBContext())
        {
            var cliente = db.Clientes.Find(IDC);

            var rodapeVM = new RodapeViewModel
            {
                Cliente = cliente
            };

            return PartialView("_skin300/_rodape", rodapeVM); // Altere aqui
        }
    }
}

That's enough for all your Controllers to know Action Rodape .

The call in View is just:

@Html.RenderAction("Rodape")

You do not need to pass the ViewModel because the ViewModel will be created by the Action of your Controller . A RodapeViewModel already exists within your Action . Just watch out for the return, you are creating a ViewModel and you are not passing it into Partial .

    
25.07.2016 / 20:38