How can I get the ViewBag value in ASP.NET MVC?

I am using ASP.NET MVC Razor viewer and I am trying to use Viewbag. The following code will not work for me. In the controller I have

ViewBag.courses = new List<dynamic>();
ViewBag.courses.Add(new { Name = "Math" });

and then in the view

@foreach(dynamic course in ViewBag.courses)
{
    <li>@course.Name</li>
}

But this gives me an error saying that the object's course has no definition for Name. The debugger gives me the value and shows everything correctly. Is there any way to make this work? (I have a workaround, I would rather use this).

Thanks in advance.

+3
source share
2 answers

Personally, I would solve this using the following:

public class Course
{
    public String Name { get; set; }
}

public class CoursesViewModel
{
    private IList<Course> courses;

    public IList<Course> Courses{
      get { return this.courses ?? (this.courses = new List<Course>()); }
      set { this.courses = value; }
    }
}

Controller:

public ActionResult Index()
{
  CoursesViewModel model = new CoursesViewModel();
  model.Courses.Add(new Course { Name = "Math" });

  return View(model: model);
}

And your opinion:

@model CoursesViewModel
@* ... *@
<ul>
@foreach (Course course in Model.Courses)
{
  <li>@course.Name</li>
}
</ul>
@* ... *@

, , MVC. , , , , ( ..). [Ab] dynamic , , , -, ( " ?", " " foo "?",...), , - , , .

+7

Brad Christie ViewModel , , , ; , . , , , ; - , , ViewModel.

, Controller to View. :

 return View((object)r.JsSerialize());

:

 @{ dynamic r = ((string)Model).JsDeserialize(); }


 @foreach (var item in r) {
 <tr>
  <td>
   @item.Person.Lastname
  </td>
  <td>
   @item.Person.Firstname
  </td>
  <td>
   @item.Person.FavoriteNumber
  </td>
  <td>
   <input type="checkbox" disabled="disabled" @(item.IsQualified ? "checked" : "") />
  </td>
 </tr>
}

, , Json Serializer ,

Json Serializer: http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx

+2

All Articles