Reputation: 959
Within my Controller I have a class called "ObjectData" that contains an ID and a string:
public class ObjectData
{
public int ObjectId { get; set; }
public string Name { get; set; }
}
I'm trying to pass a List of these to the view via ViewBag, but I don't know how to loop through the items in the array since the classtype isn't normal. I'm doing it this way because I don't want to pass a bunch of Objects and their data to the view, when I only need the ID and Name (is this a valid concern?).
I'm thinking of looping through like this:
foreach (ObjectData i in ViewBag.ParentSetIds)
{
@Html.ActionLink(i.Name, "Detail", new { objectId = i.ObjectId }, null)
}
But Razor doesn't recognize that class type. How can this be accomplished?
Upvotes: -1
Views: 4886
Reputation: 12437
Within my Controller I have a class called "ObjectData" that contains an ID and a string:
Wait, what? Why do you have a class in your controller?
I'm trying to pass a List of these to the view via ViewBag,
Just use a view model. If you are, you can make List<ObjectData>
part of it. In your controller, you load up that list (lets call it ObjectDataList
), and send it to your view.
In the view (razor), you'd have something like:
@model MyProject.MyModel
@foreach(var i in Model.ObjectDataList)
{
@Html.ActionLink(i.Name, "Detail", new { objectId = i.ObjectId }, null)
}
Edit:
For clarification, your view model could be:
public class MyModel
{
public string Title {get;set;}
public List<ObjectData> ObjectDataList {get;set;}
}
Upvotes: 0
Reputation: 9891
You could use:
foreach (var i in ViewBag.ParentSetIds)
And let the compiler determine the namespace based on the ViewBag.ParentSetIds
Upvotes: 1
Reputation: 2352
You must fully qualify your typename on the line:
foreach (Put.Your.Namespaces.Here.ObjectData i in ViewBag.ParentSetIds)
Razor do not use the same using
declaration as your controllers. You may use web.config
in the View directory to add such namespaces not to fully qualify it everytime.
Regarding the question if you should be concerned about passing such objects to view. No, there is no need to worry about it. I suggest to move the object ObjectData
from controller to the folder next to the controllers folder named ModelView
or ViewModel
and create the class here. This is something like publicly accepted "hack" to have models which represents just another view on some "real" model. It is same like when you generate MVC3 project it creates for you file AccountModels.cs
which contains exactly the same kind of models. But you find it in Model
folder, while it may be discussed if it should be rather in ViewModel
folder. Also, pass this data as Model not as the part ViewBag if it is not really just helping data.
Upvotes: 1