ASP.NET MVC中有效避免ViewBag [英] Effectively avoiding ViewBag in ASP.NET MVC

查看:20
本文介绍了ASP.NET MVC中有效避免ViewBag的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您如何处理避免 ViewBag 由于其动态错误的风险,同时避免每次都必须填充新的 ViewModel 并将其传递回视图.例如,我不想一定要更改以下内容以公开通常填充在 ViewBag 中的公共数据.

How do you deal with avoiding ViewBag due to its risk of error with being dynamic but also avoid having to populate a new ViewModel and pass it back to the view each time. For instance, I don't want to necessarily change the follow to expose common data normally stuffed in ViewBag.

[HttpGet]
void Index() 
{ 
    return View(); 
}

[HttpGet]
void Index() 
{
    var messages = new MessageCollection();
    messages.AddError("Uh oh!");

    return View(messages);
}

我将在管道中的何处添加像 ViewBag 这样的自定义和强类型属性,但让它在控制器和视图中优雅地公开.当我不需要特定的 ViewModel 时,我宁愿这样做...

Where in the pipeline would I add a property like ViewBag that is custom and strongly typed but have it exposed elegantly in the Controller and also the View. I'd rather do this when I don't need a specific ViewModel all the time...

[HttpGet]
void Index()
{
    Messages.AddError("Uh oh!");

    return View();
}

在视图方面,而不是@((IMessageCollection)ViewBag.Messages).Errors id 而是具有类似@Messages.Errors 的东西,它是强类型的并且随处可用.此外,我不想只是在 Razor 视图顶部的代码块中将其抛出.

And on the view side, instead of @((IMessageCollection)ViewBag.Messages).Errors id rather have something like @Messages.Errors that is strongly typed and available everywhere. Also, I don't want to just cast it out in a code block at the top of my Razor view.

在 WebForms 中,我会做一些事情,比如把它作为一个基本页面,然后有一个可以根据需要隐藏或显示在页面上的用户控件.随着控制器与视图分离,我不确定如何复制类似的行为.

In WebForms, I would have done something like put this a base page and then have a usercontrol that can hidden or shown on pages as needed. With the Controller decoupled from the View, I'm not sure how to replicate similar behavior.

这可能吗?最好的设计方法是什么?

Is this possible or what is the best design approach?

谢谢,斯科特

推荐答案

Razor 视图相当简单.您与单个模型进行交互,该模型是强类型的.任何你想在你的视图中强类型的东西,都需要在你的模型上.如果你的模型中有一些你不想要的东西或者一次性的东西,那么 ViewBag 是作为所有非模型数据的通用包罗万象提供的,这就是为什么它是一个动态的.强类型会限制它成为包罗万象的能力.

Razor views are fairly simplistic. You interact with a single model, which is strongly-typed. Anything you want strongly-typed in your view, then, needs to be on your model. If you have something you don't want on your model or that is one-off, then ViewBag is provided as a generic catch-all for all non-model data, which is why it is a dynamic. To be strongly-typed would limit it's ability to be a catch-all.

简短而简单:如果您想强类型地将消息添加到您的视图模型中.否则,坚持使用 ViewBag.这些都是您的选择.

Short and simple: if you want strongly-typed add Messages to your View Model. Otherwise, stick with ViewBag. Those are your choices.

这篇关于ASP.NET MVC中有效避免ViewBag的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆