Tuesday, February 19, 2013

Difference between using ViewData and ViewBag in MVC Views

For the most part, there isn’t a real technical advantage to choosing one syntax over the other. ViewBag is just syntactic sugar that some people prefer over the dictionary syntax




Although there might not be a technical advantage to choosing one format
over the other, there are some critical differences to be aware of between the
two syntaxes.

1) ViewBag works only when the key being accessed
is a valid C# identifier.
ex: if you place a value in ViewData["Key With Spaces"], you can’t access that value using ViewBag because the code won’t compile neither can you create an entry like that using ViewBag.

2)  Dynamic values cannot be passed in as parameters to extension methods. As the C# compiler must know the real type of every parameter at compile time in order for it to choose the correct extension method. If any parameter is dynamic, compilation will fail.
ex:  The below code will not compile.
    
     @Html.TextBox("name", ViewBag.Name)
To work around this,we can either use ViewData["Name"] or cast the value to a specific type:
    @Html.TextBox("name", (string)ViewBag.Name)



3 comments: