16

我注意到最新版本的 ASP.NET MVC 视图不再默认具有代码隐藏类。

现在如何将代码隐藏类添加到视图或部分视图?

4

4 回答 4

23

如何将代码隐藏页面添加到部分视图

似乎这并不是特别棘手,并且非常可行。此答案适用于 Partial但同样ViewUserControl适用于 Normal MVCViewPage

  1. 添加一个具有<view filename & extention>.cs (ie view.ascx.cs)约定的新 Class 文件

  2. 添加using System.Web.Mvc;到班级

  3. 将类更改为从 继承ViewUserControl<>
    IEpublic class Foo:ViewUserControl

  4. 将以下内容添加到视图的标题中:

    CodeBehind="View.ascx.cs" Inherits="Project.Views.Shared.View"

  5. 将文件从解决方案中复制出来并拖回以将两者重新关联在一起。这在 VS 2010+ 和 MVC 2+ 中可能不是必需的。

为此,要使用普通的 MVC 视图,您只需要从“ViewPage”继承类

于 2009-03-25T07:05:19.320 回答
4

我不确定您为什么要创建文件隐藏代码,但如果您真的这样做,那么我会考虑使用标准的网络表单方法。

我还将研究 MVC 的基础知识,以了解为什么不需要页面后面。

另一种解释

如何在没有代码隐藏的情况下使用 ASP:Chart(选项 B)

于 2009-03-25T09:38:23.337 回答
2

好的,我已经验证了解决方案,您需要注意以下几点:

CodeBehind="View.ascx.cs" Inherits="Project.Views.Shared.View"

在您的情况下,您需要根据您的命名空间和类名更改“Project.Views.Shared.View”,并且为了访问代码隐藏中的控件,您必须在代码隐藏中手动添加声明。就我而言,我需要初始化 gigaSoft proEssential 控件:

public class gigaTest2 : ViewUserControl
{
    protected global::Gigasoft.ProEssentials.PegoWeb PegoWeb1;
    protected void Page_Load(object sender, EventArgs e)
    {
        // Set Titles 
        PegoWeb1.PeString.MainTitle = "Hello ASP.NET";
        PegoWeb1.PeString.SubTitle = "";

        // One simple way of passing data, data binding also possible. //' 
        PegoWeb1.PeData.Subsets = 1;
        PegoWeb1.PeData.Points = 6;
        PegoWeb1.PeData.Y[0, 0] = 10;
        PegoWeb1.PeData.Y[0, 1] = 30;
        PegoWeb1.PeData.Y[0, 2] = 20;
        PegoWeb1.PeData.Y[0, 3] = 40;
        PegoWeb1.PeData.Y[0, 4] = 30;
        PegoWeb1.PeData.Y[0, 5] = 50;

        // Set style of chart and a few other properties //' 
        PegoWeb1.PePlot.Method = Gigasoft.ProEssentials.Enums.GraphPlottingMethod.Bar;
        PegoWeb1.PePlot.Option.GradientBars = 8;
        PegoWeb1.PeFont.FontSize = Gigasoft.ProEssentials.Enums.FontSize.Large;
    }
于 2009-05-08T15:12:12.240 回答
1

要将代码隐藏文件添加到您的 aspx 页面,同时仍允许它成为 MVC 视图的目标,请执行以下操作。

对于名为Index.aspx...

替换下面的代码......

<%@ Page Inherits="System.Web.Mvc.ViewPage" %>

<%@ Page CodeFile="Index.aspx.vb" Inherits="Home_Index" %>

然后创建一个名为Index.aspx.cs(或.vb)的文件。

partial class Home_Index : System.Web.Mvc.ViewPage
{...}

或 VB

Partial Class Home_Index
    Inherits System.Web.Mvc.ViewPage
    ...
End Class

就是这样。唯一特别的是使用正确的Mvc.ViewPage基类。

于 2016-10-27T22:29:07.857 回答