简体   繁体   中英

ASP.NET MVC ViewData.Model requires casting

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM