0

I created a Razor View by creating a new folder in my Solution under the Views folder, and then I right clicked that folder and selected "Add View".

Later, I went to my Controller folder and right clicked it, selecting "Add Controller". However, now I want to attach the view I created to my controller and it Visual Studio does not recognize that my view exists when I do:

return View("MyViewName");

How do I make Visual Studio recognize my already existing view? I would rather not resolve the issue by using Resharper to create my Razor view (since I've already created the view).

Thanks in advance!

Display Name
  • 4,672
  • 1
  • 33
  • 43
AlbertoPL
  • 11,479
  • 5
  • 49
  • 73
  • Is your view in correct (conventional) folder? – J. Holmes Sep 20 '12 at 18:14
  • 2
    did you make sure to name the view folder the same as the controller name? – Rickard Sep 20 '12 at 18:14
  • Ah, yes having the folder name and controller name match works. However, now I have to make a new view folder for every controller? Even if I am only interested in maybe one or two actions per controller? – AlbertoPL Sep 21 '12 at 06:27

2 Answers2

3

No need to write something, your folder must be named as controller. If you want other folder name, then type full path:

return View("~/Views/MyCustomFolder/MyViewName.cshtml");
webdeveloper
  • 17,174
  • 3
  • 48
  • 47
2

This is convention over configuration concept of ASP.NET MVC Your controller action should be called the same as view:

public class MyBeautifulController : Controller
{
  public ActionResult MyActionIndex()
  {
    return View();
  }
}

thank your view should be called and located like this: ~/Views/MyBeautiful/MyActionIndex.cshtml

Basically you dropping the last "Controller" in your controller class name.

This is COC (Convention Over Configuration). Now, if you want to call a view that is not called like your action, you will do the following in your action:

public class MyBeautifulController : Controller
{
  public ActionResult MyActionIndex()
  {
    return View("ViewCalledDifferently", new MyModel());
  }
}

and in this case, your view will be called and located like this: ~/Views/MyBeautiful/ViewCalledDifferently.cshtml and will accept MyModel as model type.

Hope this helps.

Display Name
  • 4,672
  • 1
  • 33
  • 43