views:

611

answers:

2

I'm working on my first ASP.NET MVC application and have a strange issue. All the tutorials in regards to using strongly typed ViewData don't require casting/eval of ViewData / Model object but I get compilation errors if I don't cast to the ViewData object

ViewData class:

public class CategoryEditViewData
{
    public Category category { get; set; }
}

Controller Action:

public ActionResult Edit(int id)
{   
    Category category = Category.findOneById(id);
    CategoryEditViewData ViewData = new CategoryEditViewData();
    ViewData.category = category;
    return View("Edit", ViewData); 
}

Works:

<%=Html.TextBox("name", 
               ((Project.Controllers.CategoryEditViewData)Model).category.Name)) %>

Doesn't Work:

<%=Html.TextBox("name", Model.category.Name)) %>

Is there something that I am doing incorrectly - or do I have to cast to the object in the view all the time?

A: 

Wait, just thought of something. In your view are you inheriting from you model????

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<namespace.Controllers.YourFormViewModel>" %>
griegs
I addedInherits="System.Web.Mvc.ViewUserControl<namespace.Controllers.CategoryEditViewData>"but now receive a e: CS0115: 'ASP.views_category_edit_aspx.GetTypeHashCode()': no suitable method found to overridecompile errordo I have to provide a GetTypeHashCode() in my CategoryEditViewData class
Rockett
I'm sorry, did you type in namespace or did you use the namespace of your controller? For example you should use Project.Controllers.CategoryEditViewData as in your code above. Sorry if that wasn't clear.
griegs
No I did type in the correct namespace. strange that it still isn't working.
Rockett
+4  A: 

First, you should move the CategoryEditViewData class out of your controllers namespace, and into your models namespace. Create a new class under the Models folder to see what it should look like. It is good practice to put your models under the models folder.

Then your Control directive should look like this:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Models.CategoryEditViewData >" %>
Lance Fisher
+1 Yeah pretty good idea
griegs