Search code examples
c#asp.net-mvcasp.net-mvc-2viewdata

ViewData.* and TModel in asp.net MVC


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?


Solution

  • 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.