Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. i tried ViewData as given in http://msdn.microsoft.com/en-us/library/system.web.mvc.viewdatadictionary.aspx

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".

How should I display the actual UserName?

Thank you very much in advance for your help.

like image 780
Lavanya Mohan Avatar asked Jan 06 '12 04:01

Lavanya Mohan


People also ask

How pass data from controller view using ViewBag?

To pass the strongly typed data from Controller to View using ViewBag, we have to make a model class then populate its properties with some data and then pass that data to ViewBag with the help of a property. And then in the View, we can access the data of model class by using ViewBag with the pre-defined property.

How do I access model value in view?

In Solution Explorer, right-click the Controllers folder and then click Add, then Controller. In the Add Scaffold dialog box, click MVC 5 Controller with views, using Entity Framework, and then click Add. Select Movie (MvcMovie. Models) for the Model class.


2 Answers

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

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

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

like image 176
Not loved Avatar answered Nov 03 '22 17:11

Not loved


It appears that you're using the Razor View Engine rather than the Web Forms View Engine. Try the following instead:

@{ 
    ViewBag.Title = "Index";   
} 
<h2>Index</h2> 
@ViewData["UserName"]
like image 34
Phil Klein Avatar answered Nov 03 '22 17:11

Phil Klein