c# - 对 ASP.NET MVC4 中的 return View() 方法感到困惑

标签 c# asp.net asp.net-mvc asp.net-mvc-4

我是 ASP.NET MVC4 的新手。我正在阅读本教程 http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-view .我不清楚 return View() 方法。为了将数据从 View 发送到 Controller ,我使用了这段代码

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

这里的 return View() 方法将数据从 View 返回到 Controller 。 为了从 Controller 发送数据到 View ,我使用了这段代码

public ActionResult Welcome(string name, int numTimes = 1)
    {
        ViewBag.Message = "Hello " + name;
        ViewBag.NumTimes = numTimes;
        return View();

    }

这是我的困惑点。 return View() 方法是否将 ViewBag.Message 和 ViewBag.NumTimes 返回到欢迎 View 。或者 Welcome View 的值返回到 Welcome 方法?

请帮我清除这部分。

最佳答案

你很困惑。您正在通过 ViewBag 将值发送到 Welcome View 。一旦 View 处理完成,您将把它返回给调用此操作的人。

线条

 ViewBag.Message = "Hello " + name;
 ViewBag.NumTimes = numTimes;

设置 Welcome View 使用的 ViewBag 值。
然后

 return View();

将 Welocme View 返回给请求 Welcome Action 的用户。

编辑1

return View() 基本上是 Controller 类中的一个函数,它返回一个 ViewResult

的实例

好像是

 ViewResult view=new ViewResult();
 return view;

或者只是

 return View()

关于 ViewBag 的更多信息
How ViewBag in ASP.NET MVC works

关于c# - 对 ASP.NET MVC4 中的 return View() 方法感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22142244/

相关文章:

C# 应用程序域到底是什么?

C# Xamarin 使用了错误的 If 子句?

c# - 类型 'ExecuteAsync' 中的方法 'System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy' 没有实现

jquery - 使用 select2 将空值添加到 DropDownListFor

c# - 如何知道哪些程序集依赖于 system.web.mvc?

c# - NHibernate 获取下一个生日

c# - 如何大写正则表达式模式?

c# - 如何在 Windows XP 中配置 Windows Activation Server (WAS) 来承载 WCF 服务?

asp.net - 侧边栏与内容和页脚重叠

c# - 根据用户声明授权访问 Controller