4

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?

1
  • No the above code should work. That's exactly how I do it and never had an issue. Is there any more code to be seen or is it really as simple as this? Commented Aug 25, 2009 at 4:44

2 Answers 2

4

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 >" %>
Sign up to request clarification or add additional context in comments.

Comments

0

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>" %>

3 Comments

I added Inherits="System.Web.Mvc.ViewUserControl<namespace.Controllers.CategoryEditViewData>" but now receive a e: CS0115: 'ASP.views_category_edit_aspx.GetTypeHashCode()': no suitable method found to override compile error do I have to provide a GetTypeHashCode() in my CategoryEditViewData class
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.
No I did type in the correct namespace. strange that it still isn't working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.