Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create ViewBag properties based on strings

Tags:

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

like image 299
bzamfir Avatar asked Oct 29 '11 00:10

bzamfir


1 Answers

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); } 
like image 151
bzamfir Avatar answered Oct 04 '22 16:10

bzamfir