【问题标题】:Why I can't use Viebag in class为什么我不能在课堂上使用 Viebag
【发布时间】:2019-07-21 06:29:47
【问题描述】:

为什么我不能在课堂上使用 ViewBag。

名称“ViewBag”在当前上下文中不存在

我用它来存储值

       if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;

用我所用的

using Shop.Data.Migrations.IServices;
using Shop.Data.Models;
using Shop.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using System.Data.Entity;
using System.Web.Mvc;

这不是控制器类

【问题讨论】:

  • 我的理解是ViewBag通常是控制器或页面的property,而不是类型。你还没有展示你是如何尝试使用它的,或者来自哪个类,但我希望你能够在正确的地方将它用作属性。如果这没有帮助,请提供更多背景信息。

标签: .net model-view-controller


【解决方案1】:

注意: Your Controller class must derives from ControllerBase 使用 ViewBag

ViewBag 属于System.Web.Mvc 命名空间。

ViewBag 是属于ControllerBase 抽象类的动态属性。

ControllerBase类实现了IController接口,增加了几个 方法和属性(例如 ViewBag)。它定义了一个摘要 ExecuteCore 方法,负责定位动作方法 并执行它。如果您选择从 ControllerBase,您必须为此提供实现 方法。

Controller 类派生自 ControllerBase。它提供了一个 ExecuteCore 方法的实现并添加了几个有用的方法 您可以在控制器中使用(例如 View()、Redirect() 等)。

总结一下——ControllerBase 和 Controller 都是内置的基础 控制器的类。内置的,因为它们是 ASP.NET MVC 框架。控制器的基类,因为如果你 从它们派生,您将创建一个控制器。

Above copied from this link to give you more idea

样本

using System.Web.Mvc;
namespace Sample.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public void Upload(string searchString)
        {
            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.UploadError = "Upload file error";

        }
    }
}

【讨论】:

    【解决方案2】:
    using System.Web.Mvc;
    

    应该足以在您的 Controller 类中使用 ViewBage:

    ViewBag.Message = "Your application description page.";
    

    您能否向我们提供更多信息?

    【讨论】:

    • 我没有在我拥有的控制器类中使用它using System.Web.Mvc;
    • 你在哪里使用它?你的类是从 Controller 扩展而来的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    • 2020-08-30
    相关资源
    最近更新 更多