根据字符串创建ViewBag属性 [英] Create ViewBag properties based on strings

查看:75
本文介绍了根据字符串创建ViewBag属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以基于字符串为ViewBag创建和使用动态属性?

Is there any way to create and use dynamic properties for ViewBag, based on strings?

类似

ViewBag.CreateProperty("MyProperty");
ViewBag.Property("MyProperty") = "Myvalue";

谢谢

推荐答案

我刚刚发现ViewData可用于为ViewBag创建此类属性

I just found out that ViewData can be used to create such properties for ViewBag

所以要创建属性CityErrorMessage,我必须使用

So to create property CityErrorMessage I have to use

ViewData.Add("CityErrorMessage", MyErrorMessage)

然后在视图中我可以使用

and then in the view I can use

@ViewBag.CityErrorMessage

我动态创建了ViewBag的属性,因为我在列表中收到带有验证错误的字段名称

I created the ViewBag's properties dynamically, because I received the name of field with validation error in a list

所以代码实际上是

foreach (ValidationError err in ValidationErrors)
{
    ViewData.Add(
        string.format("{0}ErrorMsg", err.PropertyName),
        err.ValidationErrorMessage);
}

这篇关于根据字符串创建ViewBag属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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