如何asp.net mvc的关系,以便控制器动作? [英] how does asp.net mvc relate a view to a controller action?

查看:77
本文介绍了如何asp.net mvc的关系,以便控制器动作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开了一个样品的ASP.NET MVC项目。

的HomeController 我创建了一个名为方法(动作)治法

 公众的ActionResult方法a()
{
    返回查看();
}

我有权点击治法,并创建了一个名为新视图 MethodA1

重新做了它,并创建了一个名为新视图 MethodA2


  1. 这是如何神奇的关系呢?我找了config来告诉编译器的意见 MethodAX 相关行动治法,但没有发现。


  2. 什么看法将控制器返回时,治法被称为?



解决方案

的约定是,如果你不指定视图名称,相应的视图将是操作的名称。所以:

 公众的ActionResult方法a()
{
    返回查看();
}

将呈现〜/查看/ ControllerName / MethodA.cshtml

但你也可以指定一个视图名称:

 公众的ActionResult方法a()
{
    返回视图(FooBar的);
}

现在〜/查看/ ControllerName / FooBar.cshtml 视图将被渲染。

或者,你甚至可以指定哪些不是当前控制器的意见文件夹内的一个完全合格的视图名称:

 公众的ActionResult方法a()
{
    返回视图(〜/查看/美孚/ Baz.cshtml);
}

现在显然,这一切都假定为剃刀视图引擎。如果你正在使用的WebForms,替换 .cshtml 的.aspx 的.ascx (如果您正在使用谐音工作)。

例如,如果没有认为它甚至会告诉你在哪里以什么顺序寻找意见:

记住:ASP.NET MVC是所有关于约定优于配置

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?

解决方案

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:

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

这篇关于如何asp.net mvc的关系,以便控制器动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆