Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

c# - how does asp.net mvc relate a view to a controller action?

I have opened a sample ASP.NET MVC project.

In HomeController I have created a method (action) named MethodA

public ActionResult MethodA()
{
    return View();
}

I have right clicked on MethodA and created a new view called MethodA1

Re-did it and created a new view called MethodA2.

  1. How is this magical relationship done? I looked for the config to tell the compiler that views MethodAX are related to action MethodA, but found none.

  2. What view will the controller return when MethodA is called?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The convention is that if you don't specify a view name, the corresponding view will be the name of the action. So:

public ActionResult MethodA()
{
    return View();
}

will render ~/Views/ControllerName/MethodA.cshtml.

But you could also specify a view name:

public ActionResult MethodA()
{
    return View("FooBar");
}

and now the ~/Views/ControllerName/FooBar.cshtml view will be rendered.

Or you could even specify a fully qualified view name which is not inside the views folder of the current controller:

public ActionResult MethodA()
{
    return View("~/Views/Foo/Baz.cshtml");
}

Now obviously all this assumes Razor as view engine. If you are using WebForms, replace .cshtml with .aspx or .ascx (if you are working with partials).

For example if there is no view it will even tell you where and in what order is looking for views:

enter image description here

Remember: ASP.NET MVC is all about convention over configuration.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...