我在MVC 3中看到了ViewBag。这和MVC 2中的ViewData有什么不同?


当前回答

这里ViewData和ViewBag都用于将数据从控制器传递到视图。

1. 显示数据

——ViewData是字典对象,从ViewDataDictonary类派生。

数据只允许一个请求,当页面重定向发生时ViewData值被清除。

——ViewData值必须在使用前输入。

示例:在控制器中

public ActionResult PassingDatatoViewWithViewData()
{
      ViewData["Message"] = "This message shown in view with the ViewData";
      return View();
}

在视图

@ViewData["Message"];

——ViewData是Key和Value这样的一对,Message是Key,在倒逗号中Value是Value。

数据是简单的,所以我们不能在这里使用类型转换,如果数据是复杂的,那么使用类型转换。

public ActionResult PassingDatatoViewWithViewData()
{
      var type= new List<string>
    {
        "MVC",
        "MVP",
        "MVVC"
    };
    ViewData["types"] = type;
    return View();
}

在视图中数据可以提取为

<ul>
        @foreach (var items in (List<string>)ViewData["types"])
        {
         <li>@items</li>
        }
  </ul>

2. ViewBag

——ViewBag使用动态特性。ViewBag包装了ViewData。

—在ViewBag类型铸造是必需的。

——与ViewData相同,如果重定向发生,值将变为null。

例子:

public ActionResult PassingDatatoViewWithViewBag()
{
          ViewData.Message = "This message shown in view with the ViewBag";
          return View();
}

在视图

@ViewBag.vbMessage

—对于复杂类型使用ViewBag

public ActionResult PassingDatatoViewWithViewBag()
{
          var type= new List<string>
        {
            "MVC",
            "MVP",
            "MVVC"
        };
        ViewBag.types = type;
        return View();
 }

在视图中数据可以提取为

<ul>
       @foreach (var items in ViewBag.types)
       {
         <li>@items</li>
       }
</ul>

主要的区别是ViewBag不需要类型转换,而ViewData需要类型转换。

其他回答

这里ViewData和ViewBag都用于将数据从控制器传递到视图。

1. 显示数据

——ViewData是字典对象,从ViewDataDictonary类派生。

数据只允许一个请求,当页面重定向发生时ViewData值被清除。

——ViewData值必须在使用前输入。

示例:在控制器中

public ActionResult PassingDatatoViewWithViewData()
{
      ViewData["Message"] = "This message shown in view with the ViewData";
      return View();
}

在视图

@ViewData["Message"];

——ViewData是Key和Value这样的一对,Message是Key,在倒逗号中Value是Value。

数据是简单的,所以我们不能在这里使用类型转换,如果数据是复杂的,那么使用类型转换。

public ActionResult PassingDatatoViewWithViewData()
{
      var type= new List<string>
    {
        "MVC",
        "MVP",
        "MVVC"
    };
    ViewData["types"] = type;
    return View();
}

在视图中数据可以提取为

<ul>
        @foreach (var items in (List<string>)ViewData["types"])
        {
         <li>@items</li>
        }
  </ul>

2. ViewBag

——ViewBag使用动态特性。ViewBag包装了ViewData。

—在ViewBag类型铸造是必需的。

——与ViewData相同,如果重定向发生,值将变为null。

例子:

public ActionResult PassingDatatoViewWithViewBag()
{
          ViewData.Message = "This message shown in view with the ViewBag";
          return View();
}

在视图

@ViewBag.vbMessage

—对于复杂类型使用ViewBag

public ActionResult PassingDatatoViewWithViewBag()
{
          var type= new List<string>
        {
            "MVC",
            "MVP",
            "MVVC"
        };
        ViewBag.types = type;
        return View();
 }

在视图中数据可以提取为

<ul>
       @foreach (var items in ViewBag.types)
       {
         <li>@items</li>
       }
</ul>

主要的区别是ViewBag不需要类型转换,而ViewData需要类型转换。

我能建议你不要用吗?

如果你想“发送”数据到你的屏幕上,发送一个强类型对象(又名ViewModel),因为它更容易测试。

如果你绑定到某种类型的“模型”,并拥有随机的“viewbag”或“viewdata”项,那么这会使自动化测试变得非常困难。

如果您正在使用这些,请考虑如何重构并仅使用ViewModels。

Although you might not have a technical advantage to choosing one format over the other, you should be aware of some important differences between the two syntaxes. One obvious difference is that ViewBag works only when the key you’re accessing is a valid C# identifi er. For example, if you place a value in ViewData["Key With Spaces"], you can’t access that value using ViewBag because the code won’t compile. Another key issue to consider is that you cannot pass in dynamic values as parameters to extension methods. The C# compiler must know the real type of every parameter at compile time in order to choose the correct extension method. If any parameter is dynamic, compilation will fail. For example, this code will always fail: @Html.TextBox("name", ViewBag.Name). To work around this, either use ViewData["Name"] or cast the va

我注意到ViewData和ViewBag之间的一个主要区别是:

ViewData:它将返回object,不管你给它赋了什么,需要再次类型转换回原始类型。

ViewBag:它足够聪明,可以返回你分配给它的确切类型,不管你分配的是简单类型(即int,字符串等)还是复杂类型。

例如:控制器代码。

 namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            Products p1 = new Products();
            p1.productId = 101;
            p1.productName = "Phone";
            Products p2 = new Products();
            p2.productId = 102;
            p2.productName = "laptop";

            List<Products> products = new List<Products>();
            products.Add(p1);
            products.Add(p2);
            ViewBag.Countries = products;
            return View();
        }
    }
    public class Products
    {
        public int productId { get; set; }
        public string productName { get; set; }
    }
}

视图代码。

<ul>
            @foreach (WebApplication1.Controllers.Products item in ViewBag.Countries)
            {
            <li>@item.productId &nbsp;&nbsp;&nbsp;@item.productName</li>
            }
        </ul>

屏幕输出。

它使用c# 4.0动态特性。它实现了与viewdata相同的目标,应该避免使用强类型视图模型(与viewdata应该避免的方式相同)。

基本上它取代了魔法字符串:

ViewData["Foo"]

具有神奇属性:

ViewBag.Foo

你没有编译时安全性。

我继续指责微软在MVC中引入了这个概念。

属性的名称区分大小写。