ASP.NET MVC ViewData.Model requires casting

I am working on my first ASP.NET MVC application and am experiencing a strange problem. All tutorials on using strongly typed ViewData do not require casting / eval of the ViewData / Model object, but I get compilation errors if I don't pass the ViewData object p>

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

Does not work:

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

Is there something I am doing wrong - or do I need to throw at an object in a view all the time?

+4
source share
2 answers

You must first transfer the CategoryEditViewData class from the namespace of your controllers and into the model namespace. Create a new class in the Models folder to see how it will look. It’s good practice to place your models under the model folder.

Then your Control directive should look like this:

 <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Models.CategoryEditViewData >" %> 
+4
source

Wait, just think about something. In your opinion, do you inherit a model from you ????

 <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<namespace.Controllers.YourFormViewModel>" %> 
0
source

All Articles