Getting custom type from TempData asp.net mvc 2

882 views Asked by At

I have a custom class MyCustomType. In that class I have a property MyCustomProperty of type bool and another property MyCustomProperty1 of type bool also.

I need to check if MyCustomProperty is true in my View. I`m doing the following thing:

<%if ( TempData[ViewDataConstants.MyCustomTypeKey] != null && ((MyCustomType)TempData[ViewDataConstants.MyCustomTypeKey]).MyCustomProperty %>show some custom content.

But for some reason when Im running it I see error message that MyCustomTYpe could not be found are you missing an assembly reference bla-bla-bla. MyCustomType is in my controller its public and to check I even added a reference to the view. But it keep saying that there`s no MyCustomType class. What am I doing wrong?

Interesting, for some reason when I moved it to Common from Controllers namespace it suddenly worked. Still dont see why its not working while in Controllers namespace. Both namespaces were included explicitly in the view.

1

There are 1 answers

1
Darin Dimitrov On BEST ANSWER

No idea why it didn't work but quite honestly having all this code in a view looks wrong to me. Maybe it's just like me, Visual Studio doesn't like writing C# code in a view :-).

This should be a property on your view model:

public class MyViewModel
{
    public bool MyCustomProperty { get; set; }
}

and inside your controller:

public ActionResult Foo()
{
    var model = TempData[ViewDataConstants.MyCustomTypeKey] as MyCustomType ?? new MyCustomType();
    var viewModel = Mapper.Map<MyCustomType, MyViewModel>(model);
    return View(viewModel);
}

and finally inside your view:

<% if (Model.MyCustomProperty) { %>
    show some custom content.
<% } %>

Now you no longer need any usings, castings, ... in the view.