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);
}
Share:
20,461

Related videos on Youtube

bzamfir
Author by

bzamfir

Updated on June 05, 2020

Comments

  • bzamfir
    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
    Caleb Jares almost 11 years
    Thank you! This took a long time to find.
  • anIBMer
    anIBMer almost 11 years
    thank you for explaining the relationship between ViewBag and ViewData
  • Matty
    Matty over 10 years
    Should be noted that you can use ViewData["NameHere"] to dynamically get the value of the items you have stored.
  • JEuvin
    JEuvin almost 7 years
    Exception thrown: 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' in Microsoft.CSharp.dll Additional information: 'System.Dynamic.DynamicObject' does not contain a definition for 'Add'
  • Norbert Norbertson
    Norbert Norbertson almost 7 years
    I will check the project I have with this code working. It seems others are not able to replicate it.
  • Arsman Ahmad
    Arsman Ahmad about 6 years
    Having error: An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll but was not handled in user code