@Html.Action in _Shared error when sending a Viewmodel by Controller

Asked

Viewed 34 times

1

In my _Shared have a Partialview calling for _rodape.cshtml but now she will need to receive a Viewmodel which will have various data.

Like I don’t want to create a Action in each Controller, I thought I’d create a Controller called _Rodape, and all the others Controller inherit from that:

It even spun, but I can’t send my Viewmodel.

As it turned out: _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 the _rodape.cshtml try to use @Model.AlgumaCoisa makes the mistake:

System.Nullreferenceexception:

I thought I’d send it straight from _shared the Viewmodel to the Partial, something like:

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

But I need a controller to perform various business logics. How to send the Viewmodel for a Partialview within a Shared?

1 answer

0


The correct way to do this is by making a derivation of oneself Controller, thus:

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 alone is enough for all your Controllers know the Action Rodape.

The call in View is just:

@Html.RenderAction("Rodape")

No need to pass the Viewmodel because the Viewmodel will be created by Action of your Controller. There is already the creation of a RodapeViewModel within your Action. Just watch out for the return, that you’re creating a Viewmodel and is not passing him into the Partial.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.