简体   繁体   中英

ViewBag RuntimeBinderException (MVC 4, ASPX)

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM