Create ViewBag properties based on strings
Asked Answered
L

2

26

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

Lustre answered 29/10, 2011 at 0:25 Comment(0)
L
55

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);
}
Lustre answered 29/10, 2011 at 0:31 Comment(2)
thank you for explaining the relationship between ViewBag and ViewDataJadda
Should be noted that you can use ViewData["NameHere"] to dynamically get the value of the items you have stored.Shrovetide
C
-3

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);
            }
Complemental answered 17/5, 2016 at 15:5 Comment(3)
Exception thrown: 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' in Microsoft.CSharp.dll Additional information: 'System.Dynamic.DynamicObject' does not contain a definition for 'Add'Propeller
I will check the project I have with this code working. It seems others are not able to replicate it.Complemental
Having error: An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll but was not handled in user codeThacher

© 2022 - 2024 — McMap. All rights reserved.