ViewBag RuntimeBinderException (MVC 4, ASPX)
Asked Answered
L

1

4

I started up a Default MVC 4 project using the ASPX engine (not Razor), and everything works fine.
I can use

<% Model.Name %>

and

<% Model.Rating %>

for book ratings (instead of the Restaurant Review that is up on the asp.net/mvc tutorials site). However, my code errors on the <% ViewBag.Message %>

...so for some reason, when inheriting from the "BookReviewer" Class within the BookReview model, I can view the Model information but not the Viewbag? Am I missing something? Code below.

[Controller] HomeController.cs:

    public class HomeController : Controller
    {
        var model = new BookReview()
        {
            Name = "Pro jQuery For Noobs",
            Rating = 7
        };
        return View(model);
    }

[Model] BookReview.cs

    namespace Bookreview.Models
    {
            public class BookReview
            {
                    public string Name { get; set; }
                    public int Rating { get; set; }
            }
    }

[View] Index.aspx:

    <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<BookRevew.Models.BookReviewer>" %>
    <asp:Content ID="indexFeatured" ContentPlaceHolderID="FeaturedContent" runat="server">
        <h2>
            <% ViewBag.Message %>
            <% Model.Name %>
            <% Model.Rating %>
        </h2>
    </asp:content>
Lightface answered 30/1, 2013 at 22:30 Comment(2)
I don't see anywhere where you are setting ViewBag.Message. Nor do I see a BookReviewer class you mention. Is there code you're not posting?Hematite
I set it in another ActionResult: public ActionResult About() { ViewBag.Message = "This is a test"; return View(); } Is it not allowed to be referenced outside of other ActionResults?Lightface
B
6

As we can see by your comments, you are setting the ViewBag.Message in another controller. The ViewBag is only for data for the view that was set by the controller that served the view.

If you need to send it from another controller, you should use a parameter in your action method, then you can set the ViewBag.Message to the passed in parameter.

Blissful answered 30/1, 2013 at 22:54 Comment(2)
Thank you, that makes much more sense than the way that I had read it in my book.Lightface
Phrased like that that is technically not quite true. You can ofc. go var otherController = new OtherController(); return otherController.Whatever() and the view will have access to the data placed in the ViewBag by the original controller. So it's not that "set by the controller serving the view". But rather: In Index() excution path it has never been set. To confirm this, one can set a breakpoint on the line that sets the Viewbag.Message. When debugging, it won't be hit.Kessinger

© 2022 - 2024 — McMap. All rights reserved.