简体   繁体   中英

Creating a View Before the Controller in ASP.NET MVC

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!

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");

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM