Create ViewBag properties based on strings
20,461
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);
}
Related videos on Youtube
Author by
bzamfir
Updated on June 05, 2020Comments
-
bzamfir almost 4 years
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
-
Caleb Jares almost 11 yearsThank you! This took a long time to find.
-
anIBMer almost 11 yearsthank you for explaining the relationship between ViewBag and ViewData
-
Matty over 10 yearsShould be noted that you can use
ViewData["NameHere"]
to dynamically get the value of the items you have stored. -
JEuvin almost 7 yearsException thrown: 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' in Microsoft.CSharp.dll Additional information: 'System.Dynamic.DynamicObject' does not contain a definition for 'Add'
-
Norbert Norbertson almost 7 yearsI will check the project I have with this code working. It seems others are not able to replicate it.
-
Arsman Ahmad about 6 yearsHaving error: An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll but was not handled in user code