views:

136

answers:

2

After a week of asp.net mvc2, I still haven’t understood the advantages of ViewData.model or rather how I can properly utilize Viewdata. Can some teach me how to use Viewdata properly?

Also what’s TModel that’s associated with viewdata? How does one utilize TModel? The viewdata explanation in spark view engine talks about TModel and I couldn’t get a clue of how I can use it in my projects. Can someone help me?

+2  A: 

ViewData.Model is something that you can set in controller action and gets passed to the View where you can access it like this

<%=ViewData.Model.Description %>

or

<%=Model.Description %>

that is, if the class that you are passing to the View contains property Description:

public ActionResult GetInstance(string id)
{
    MyContent content = GetContentFromDatastore(id);
    return View(content);
}

with this MyContent class

MyContent
{
    string id;
    string description;
}

Basically you are sending an instance of a class (an object with its properties set, most likely taken from the database) back to the View and display its data in the View, View being the ascx or aspx file, that eventually gets display to the user/visitor. This is very simple example but it is unclear what exactly you want and how much you already know. But try to leave Spark (and other View Engines) out of the question for now until you know the ASP.NET MVC basics well.

mare
A: 

Mare is correct, you can use your models in your view by accessing the ViewData.ModelName.PropertyName item.

Also while in your controller you can set certain key/value pairs in the ViewData dictionary:

ViewData["Address1"] = "2222 Somewhere";

And then access it in your view:

<%= Html.Encode(ViewData["Address1"]) %>

Obviously it wouldn't be ideal to use a key/value pair to handle all of your data, thats why you can create your own classes to encapsulate data, and pass THOSE to your view for easier manipulation.

Jack