0

I have two Controllers CustomerController, CompanyController . if I need to load a view which is at View/Company, but both Customer and Company controller need to use it .. I have two ways to load it in CustomerController ..

First

public class CustomerController : Controller
    {
        public ActionResult Companies()
        {            
            var companies = GetCompanies();                
            return View("../Company/Companies", companies);
        }
    }

Second

Shift the "Companies" view to View/Shared folder and then both controller will be able to access it.

Which approach is correct and better .. which will perform faster .. etc .. please share suggestions

NMathur
  • 829
  • 1
  • 17
  • 35
  • 1
    if both the controllers need to use it, then moving it to shared is preferred. – Kumar_Vikas Jan 08 '18 at 05:57
  • You can just pass the controller name and view name as separate arguments to the "View" methods, which is more robust since MVC does the routing and creates the correct URL for you. Anyway there's nothing stopping you using the first method, the fact the View A is in a different folder to view B in does not stop another A from redirecting to B, or vice versa. – ADyson Jan 08 '18 at 06:16
  • @ADyson return view does take controller name as argument .. this option is in RedirectToAction .. – NMathur Jan 08 '18 at 08:32
  • @Kumar_Vikas can you please share why Shared folder is preferred .. I also prefer Shared folder, but does not have any logical answer for this – NMathur Jan 08 '18 at 08:33
  • 1
    In that case you would need to use RedirectToAction...but what's the problem with that? Either way you shouldn't build the URL by hand like you're doing. – ADyson Jan 08 '18 at 09:14
  • @ADyson thanks for sharing your opinion .. so building Url is not good .. we should use shared folder .. right? .. and "this option is in RedirectToAction" was for "You can just pass the controller name and view name as separate arguments to the "View" methods" ..may be my understanding was wrong .. I thought you are saying that I can pass desired controller name in "return View()" as argument .. not so good in English – NMathur Jan 08 '18 at 09:22
  • 1
    Yes I was saying that, but it's my mistake. You can only call `return View` to go to a view within the same controller, You are right, RedirectToAction is required in order to go to a view in another controller. So, I think that's what you probably should do. No need to move the view into the shared folder as far as I can see. – ADyson Jan 08 '18 at 09:34
  • @ADyson sorry my mistake .. I should be more specific .. now I have updated the question .. I need to pass the entire model to the view .. probably an entire collection of object – NMathur Jan 08 '18 at 09:52
  • 1
    See https://stackoverflow.com/questions/22505674/can-we-pass-model-as-a-parameter-in-redirecttoaction for how you can get round that if you want to. – ADyson Jan 08 '18 at 10:01

0 Answers0