s.k.paul
s.k.paul

Reputation: 7291

Override View() in asp.net mvc

I have the follow base controller-

public abstract class BaseController : Controller
{
     protected string BaseUrl = "URL";
}

All other controller inherit the above base controller-

public class MyController : BaseController
{       
    public ActionResult Something()
    {
        ViewBag.BaseUrl = base.BaseUrl;
        return View();
    }
}

I don't want to write ViewBag.BaseUrl = base.BaseUrl; in every controller action method. Rather, I would to automatically pass this base url to the related view. Is it possible by overriding View()?

An example would be better for me.

Upvotes: 1

Views: 773

Answers (1)

CodingYoshi
CodingYoshi

Reputation: 26989

If all controllers derive this then just put it in here:

public abstract class BaseController : Controller
{
     protected string BaseUrl = "URL";
     public BaseController()
     {
         ViewBag.BaseUrl = base.BaseUrl;
     }   
}

I would even make it private if I do not want inheriting classes to overwrite it.

Upvotes: 3

Related Questions