有效地避免了ViewBag在ASP.NET MVC [英] Effectively avoiding ViewBag in ASP.NET MVC

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

问题描述

你是如何处理以避免ViewBag由于其错误的危险性是动态的,但也避免填充一个新视图模型,每一次传回的看法。举例来说,我不想一定改变后续暴露通常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属性是自定义的强类型,但有它在控制器优雅暴露,也是观。我宁愿这样做时,我并不需要一个特定的视图模型所有的时间...

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。另外,我不想只投它在code座在我的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?

谢谢,
斯科特

Thanks, Scott

推荐答案

剃须刀意见是相当简单的。你用一个模型,它是强类型的相互作用。要在您的视图强类型的话,那么,需要在您的模型。如果您有什么你不希望你的模型,或者是一次性的,那么 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.

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

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