DotnetSparrow
DotnetSparrow

Reputation: 27996

passing anonymous object to view

I want to pass two values from controller action to asp.net MVC 3 Razor view. I am doing like this in action method:

var model = new { reportid = rid, refno = refernumber};
return View(model );

but when i try to access it in view like this:

@Model.reportid

I get, object doesn't contain property reportid

How can I pass multiple values without using viewbag ?

Upvotes: 8

Views: 8425

Answers (2)

Mikhail Fiadosenka
Mikhail Fiadosenka

Reputation: 321

Another way to accomplish this task - is to use ExpandoObject.

dynamic model = new System.Dynamic.ExpandoObject();
model.reportid = 123
model.refno = 456;

Set the view model type to dynamic:

@model dynamic

@Model.reportid
@Model.refno

Upvotes: 2

rouen
rouen

Reputation: 5124

Well, i strongly recommend you to use ViewModel class. But if for some reason you have phobia of extra viewmodel classes, you can use C# feature called Tuple

var model = Tuple.Create(firstObject, secondObject)

and then your view will be of type Tuple, for example

@model Tuple<int, string>

and you can access them like this

@Model.Item1

And then you can congratulate yourself, you have achieved nice mess with hidden meaning :)

Upvotes: 17

Related Questions