LoginSignup
2
4

More than 5 years have passed since last update.

【C#】【ASP.NET】小ネタ・単一のaspxファイルの処理をCSファイルに切り分ける

Posted at

続き物です。

前の記事:【C#】小ネタ・IISだけインストールしてさくっとASP.NETのHello World!を表示する
https://qiita.com/tabelog2001/items/3532972763db8a70bf1c

ますます「どこに需要があんだよ」的記事になっていきますが、さくっと試すために単一のaspxファイルのコードを提示してコレ一個放り込めば動くんすよ、というのが前回投稿の記事のシメ。

そのクソコードを
「処理部分だけCSファイルに切り分けたければこうしてください」
というのが今回のおハナシ。

前回から変更したhelloworld.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="helloworld.aspx.cs" Inherits="helloworld" %>

<html>
<head runat="server"></head>
<body>
  <form id="form1" runat="server">
    <div>
      <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
      <asp:Label ID="Label1" runat="server" Text="Label" />
    </div>
  </form>
</body>
</html>

変えたところは<script runat="server">タグを削ったのと、ヘッダに以下の記述を加えたところ。

CodeFile="helloworld.aspx.cs" Inherits="helloworld"

これで、このaspxファイルはhelloworld.aspx.csの中のhelloworldクラスを参照するんだぜ、とIISくんが理解できてそっちの処理を見に行くようになります。

切り分けたhelloworld.aspx.cs

using System;
using System.Web;
using System.Web.UI;

public partial class helloworld : System.Web.UI.Page
{
  protected void Button1_Click(object sender, EventArgs e)
  {
      Label1.Text = "Hello,World!";
  }
}

ちなみにpartial識別子は要るらしい。削ったら怒られました。
以上。

2
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4