ViewBag RuntimeBinderException(MVC 4,ASPX)RuntimeBinderException、ViewBag、ASPX、MVC

2023-09-05 04:08:25 作者:南棠

我开始了一个默认的MVC使用 ASPX 发动机(未剃刀)4项目,一切工作正常。 我可以使用

<%Model.Name%>

<%Model.Rating%>

有关本书评级(而不是餐厅评论即达上asp.net/mvc教程网站)。然而,我的code上的错误 <%ViewBag.Message%>

...所以出于某种原因,从BookReviewer类的书评模型中继承的时候,我可以查看模型信息,而不是 Viewbag ?我失去了一些东西?低于code。

[控制器] HomeController.cs:

 公共类的HomeController:控制器
    {
        VAR模型=新书评()
        {
            NAME =临的jQuery对于菜鸟,
            等级= 7
        };
        返回查看(模型);
    }
 
七天学会MVC 2 数据传递

[产品型号] BookReview.cs

 命名空间Bookreview.Models
    {
            公共类书评
            {
                    公共字符串名称{;组; }
                    公众诠释评级{获得;组; }
            }
    }
 

[查看] Index.aspx的:

 <%@页标题=LANGUAGE =C#的MasterPageFile =〜/查看/共享/的Site.Master继承=System.Web.Mvc.ViewPage< BookRevew.Models.BookReviewer>中%>
    < ASP:内容ID =indexFeaturedContentPlaceHolderID =FeaturedContent=服务器>
        < H2>
            <%ViewBag.Message%GT;
            <%Model.Name%GT;
            <%Model.Rating%GT;
        < / H>
    < / ASP:内容>
 

解决方案

我们可以通过您的意见看,您正在设置 ViewBag.Message 的另一个控制器。该 ViewBag 是仅适用于由该服务的视图控制器设置视图数据

如果你需要从另一个控制器发送,你应该在你的操作方法使用的参数,那么你可以设置 ViewBag.Message 于传入的参数。

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.