ViewBag RuntimeBinderException (MVC 4, ASPX)

2019-05-11 03:43发布

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>

1条回答
等我变得足够好
2楼-- · 2019-05-11 04:38

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.

查看更多
登录 后发表回答