简体   繁体   English

如何在asp.net中将值从控制器传递到视图?

[英]How to pass values from controller to view in asp.net?

I am developing an application where I need to pass the value of username from a controller to a view. 我正在开发一个应用程序,我需要将username的值从控制器传递给视图。 i tried ViewData as given in http://msdn.microsoft.com/en-us/library/system.web.mvc.viewdatadictionary.aspx 我尝试了http://msdn.microsoft.com/en-us/library/system.web.mvc.viewdatadictionary.aspx中给出的ViewData。

My code in controller is 我在控制器中的代码是

public ActionResult Index(string UserName, string Password)
{
        ViewData["UserName"] = UserName;
        return View();
}

where username and password are obtained from another form. 从其他表单获取用户名和密码。

And the code in the view is 而视图中的代码是

@{
    ViewBag.Title = "Index";  
}
<h2>Index</h2>
<%= ViewData["UserName"] %>

But when I run this code, the display shows <%= ViewData["UserName"] %> instead of the actual username say, for example "XYZ". 但是当我运行此代码时,显示屏显示<%= ViewData [“UserName”]%>而不是实际的用户名,例如“XYZ”。

How should I display the actual UserName? 我该如何显示实际的UserName?

Thank you very much in advance for your help. 非常感谢您的帮助。

You're using razor syntax here but you're trying to mix it with older asp.net syntax, use 你在这里使用的是razor语法,但是你正试图将它与旧的asp.net语法混合使用

@ViewData["UserName"] 

instead 代替

Also, normally you wouldn't use the view bag to pass data to the view. 此外,通常您不会使用视图包将数据传递给视图。 Standard practice is to create a model (a standard class) with all of the bits of data your View (page) wants then pass that model to the view from your controller (return View(myModel);) 标准做法是创建一个模型(标准类),其中包含View(页面)所需的所有数据位,然后将该模型传递给控制器​​的视图(返回View(myModel);)

To do this you also need to declare the type of model you're using in your view 为此,您还需要声明视图中使用的模型类型

@model Full.Namespace.To.Your.MyModel

read http://msdn.microsoft.com/en-us/gg618479 for a basic mvc models tutorial 阅读http://msdn.microsoft.com/en-us/gg618479获取基本的mvc模型教程

It appears that you're using the Razor View Engine rather than the Web Forms View Engine. 您似乎正在使用Razor View Engine而不是Web窗体视图引擎。 Try the following instead: 请尝试以下方法:

@{ 
    ViewBag.Title = "Index";   
} 
<h2>Index</h2> 
@ViewData["UserName"]

The 'ViewBag' is a holdover from MVC2. 'ViewBag'是MVC2的延续。 MVC3 development should use strongly typed 'ViewModel's. MVC3开发应该使用强类型的'ViewModel'。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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