Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 4 same logic with different view folders

I am new to MVC and started with MVC 4. I want to make an online shop application.

-Same shopping logic will be used by two different web sites/domains.

-And the views must alter according to domain name and their mobile versions.

Logic file structe is like this:

Controllers/HomeController.cs
Controllers/ProductController.cs
Models/Home.cs
Models/Product.cs

View file structure for first domain:

Views/my_1st_Domain/Home/Index.cshtml
Views/my_1st_Domain/Home/Index.Mobile.cshtml
Views/my_1st_Domain/Home/Terms.cshtml
Views/my_1st_Domain/Home/Terms.Mobile.cshtml
Views/my_1st_Domain/Product/Index.cshtml
Views/my_1st_Domain/Product/Index.Mobile.cshtml
Views/my_1st_Domain/Product/Detail.cshtml
Views/my_1st_Domain/Product/Detail.Mobile.cshtml

View file structure for second domain:

Views/my_2nd_Domain/Home/Index.cshtml
Views/my_2nd_Domain/Home/Index.Mobile.cshtml
Views/my_2nd_Domain/Home/Terms.cshtml
Views/my_2nd_Domain/Home/Terms.Mobile.cshtml
Views/my_2nd_Domain/Product/Index.cshtml
Views/my_2nd_Domain/Product/Index.Mobile.cshtml
Views/my_2nd_Domain/Product/Detail.cshtml
Views/my_2nd_Domain/Product/Detail.Mobile.cshtml

The question is: How do switch between domain specific view folders automatically?

It can be done manually by repeating this line everywhere:

return View("~/Views/" + getDomainSpecificFolder() + "/Home/Index" + getMobileSuffixIfNeeded() + ".cshtml");

Is there any easier way to change base view folder globally with one shot?

Thanks in advance,

like image 787
mustafa öztürk Avatar asked Jan 04 '14 22:01

mustafa öztürk


1 Answers

You can make own ViewEngine, and return specific view depending on your current domain. In controller code you just need to return usual

return View();

And all logic will be handled in custom ViewEngine.

Here is some details about it -

  • http://weblogs.asp.net/imranbaloch/archive/2011/06/27/view-engine-with-dynamic-view-location.aspx
  • http://www.headcrash.us/blog/2011/10/custom-view-engine-for-localized-views-with-asp-net-mvc-razor/

Basically you need to make CustomViewEngine class, that inherits RazorViewEngine and register it in global.asax. Then in that class you need to overwrite FindView method, that will use path for view based your domain.

like image 110
Sergey Litvinov Avatar answered Oct 17 '22 05:10

Sergey Litvinov