【问题标题】:ASP.NET MVC ViewData.Model requires castingASP.NET MVC ViewData.Model 需要强制转换
【发布时间】:2009-08-25 04:41:32
【问题描述】:

我正在开发我的第一个 ASP.NET MVC 应用程序,但遇到了一个奇怪的问题。所有关于使用强类型 ViewData 的教程都不需要对 ViewData / Model 对象进行强制转换/评估,但如果我不强制转换为 ViewData 对象,则会出现编译错误

ViewData 类:

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

控制器动作:

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

作品:

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

不起作用:

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

有什么我做错了 - 还是我必须一直投射到视图中的对象?

【问题讨论】:

  • 上面的代码不应该工作。我就是这样做的,从来没有遇到过问题。有没有更多的代码可以看,还是真的这么简单?

标签: c# asp.net asp.net-mvc


【解决方案1】:

首先,您应该将 CategoryEditViewData 类移出控制器命名空间,并移入模型命名空间。在 Models 文件夹下创建一个新类,看看它应该是什么样子。最好将模型放在模型文件夹下。

那么你的 Control 指令应该是这样的:

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

【讨论】:

    【解决方案2】:

    等等,刚刚想到一件事。在你看来,你是从你的模型继承而来的吗????

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

    【讨论】:

    • 我添加了 Inherits="System.Web.Mvc.ViewUserControl" 但现在收到一个 e: CS0115: 'ASP.views_category_edit_aspx.GetTypeHashCode()': 找不到合适的方法覆盖编译错误我是否必须在我的 CategoryEditViewData 类中提供 GetTypeHashCode()
    • 对不起,您输入的是命名空间还是使用了控制器的命名空间?例如,您应该在上面的代码中使用 Project.Controllers.CategoryEditViewData。抱歉,如果不清楚。
    • 不,我确实输入了正确的命名空间。奇怪的是它仍然无法正常工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 2014-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多