如何从控制器传递值来查看asp.net? [英] How to pass values from controller to view in asp.net?

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

问题描述

我开发一个应用程序,我需要从控制器到视图通过用户名的值。
我试图ViewData的在<给定href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.viewdatadictionary.aspx\">http://msdn.microsoft.com/en-us/library/system.web.mvc.viewdatadictionary.aspx

I am developing an application where I need to pass the value of username from a controller to a view. i tried ViewData as given in http://msdn.microsoft.com/en-us/library/system.web.mvc.viewdatadictionary.aspx

在我的控制器code是

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.

和在视图中code是

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

但是,当我运行这个code,显示屏显示&LT;>而不是实际的用户名(%)=计算机[用户名]%的人说,例如XYZ

But when I run this code, the display shows <%= ViewData["UserName"] %> instead of the actual username say, for example "XYZ".

我应该如何显示实际的用户名?

How should I display the actual UserName?

非常感谢你提前为您的帮助。

Thank you very much in advance for your help.

推荐答案

您正在使用剃刀语法,在这里,但你试图把它与老asp.net的语法混合,用

You're using razor syntax here but you're trying to mix it with older asp.net syntax, use

@ViewData["UserName"] 

而不是

另外,通常你不会使用该视图袋将数据传递到视图。标准的做法是创建具有所有数据的视图(页)位的模式(标准级)想要再传递模型视图从控制器(返回查看(基于myModel);)

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

要做到这一点,你还需要声明模型的类型你使用你的看法

To do this you also need to declare the type of model you're using in your view

@model Full.Namespace.To.Your.MyModel

http://msdn.microsoft.com/en-us/gg618479 一个基本的MVC模型教程

read http://msdn.microsoft.com/en-us/gg618479 for a basic mvc models tutorial

这篇关于如何从控制器传递值来查看asp.net?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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