Create ViewBag properties based on strings

馋奶兔 提交于 2020-01-12 11:16:53

问题


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

Something like

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

Thank you


回答1:


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

So to create property CityErrorMessage I have to use

ViewData.Add("CityErrorMessage", MyErrorMessage)

and then in the view I can use

@ViewBag.CityErrorMessage

EDIT:

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

So the code actually is

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



回答2:


Update: I belatedly realised that this code comes from a Nancy project and Nancy implements it's own ViewBag so this code does not work with .Net MVC3 and does not answer the question. However, it might be argued that the question could be solved by switching to Nancy.

I found ViewBag has an Add method so you can do this:

foreach(var row in model)
            {
                ViewBag.Add(row.resourceName, row.content);
            }


来源:https://stackoverflow.com/questions/7936150/create-viewbag-properties-based-on-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!