先从控制器里添加视图
视图引擎选"ASPX(C#)",使用布局或模板页不要选。
在Views\EAV目录里,生成的aspx是个单独的页面,没有代码文件,所以代码也要写在这个文件里。
<%
@
Page
Language
="C#"
Inherits
="System.Web.Mvc.ViewPage<dynamic>"
%>
<%
@
Import
Namespace
="System"
%>
<%
@
Import
Namespace
="System.Data"
%>
<%
@
Import
Namespace
="System.Web.UI"
%>
<%
@
Import
Namespace
="System.IO"
%>
<%
@
Import
Namespace
="System.Web.UI.WebControls"
%>
<
script
type
="text/C#"
runat
="Server">
protected
void
Page_Load
(
object
sender
,
EventArgs
e
)
{
int
i
;
Response
.
Write
(
"<h2>Page_Load</h2><br/>"
);
Calendar1
.
SelectedDate
=
new
DateTime
(2013, 1, 1);
for
(
i
= 1;
i
<= 100; ++
i
)
{
lstRec
.
Items
.
Add
(
string
.
Format
(
"Item{0:00}"
,
i
));
}
}
</
script
>
<!
DOCTYPE
html
>
<
html
>
<
head
runat
="server">
<
title
>
Index
</
title
>
</
head
>
<
body
>
<
form
id
="form1"
runat
="server">
<
div
>
<
asp
:
Calendar
ID
="Calendar1"
runat
="server"></
asp
:
Calendar
>
<
br
/>
<
asp
:
listbox
ID
="lstRec"
runat
="server"
Width
="150"></
asp
:
listbox
>
</
div
>
</
form
>
</
body
>
</
html
>
这样就可以使用设计界面了
ASPX(C#)视图引擎默认只生成一个aspx文件,都写在一个文件里毕竟不是好主意,能不能像传统的aspx的代码分离结构呢?答案是可以的!
先加一个Controller:EAVController,仍然按上面的办法加视图。
然后在EAV目录右单击,添加新建项。
选Web窗体,名称那肯定是index啦。
好,我们需要的出现了。但是运行是要出错滴。
那就需要改一下了,打开代码文件index.aspx.cs,加一个命名空间的引用:using System.Web.Mvc;index页面类继承于System.Web.UI.Page是不行的,改成System.Web.Mvc.ViewPage。ViewPage是Page的子类。
------index.aspx.cs
文件
------
using
System
;
using
System
.
Collections
.
Generic
;
using
System
.
Linq
;
using
System
.
Web
;
using
System
.
Web
.
UI
;
using
System
.
Web
.
UI
.
WebControls
;
namespace
FirstMvc
.
Views
.
EAV
{
public
partial
class
index
:
System
.
Web
.
Mvc
.
ViewPage
{
protected
void
Page_Load
(
object
sender
,
EventArgs
e
)
{
Response
.
Write
(
"<h2>EAV Page_Load</h2><hr/><br/>"
);
for
(
int
i
= 1;
i
<= 100; ++
i
)
{
lstRec
.
Items
.
Add
(
string
.
Format
(
"Item{0:00}"
,
i
));
}
}
}
}
------index.aspx
文件
------
<%
@
Page
Language
="C#"
AutoEventWireup
="true"
CodeBehind
="index.aspx.cs"
Inherits
="FirstMvc.Views.EAV.index"
%>
<!
DOCTYPE
html
PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html
xmlns
="http://www.w3.org/1999/xhtml">
<
head
runat
="server">
<
title
></
title
>
</
head
>
<
body
>
<
form
id
="form1"
runat
="server">
<
div
>
<
asp
:
ListBox
ID
="lstRec"
runat
="server"
Width
="150"></
asp
:
ListBox
>
</
div
>
</
form
>
</
body
>
</
html
>
看看运行效果:
有个注意的地方,因为mvc处理的请求而不是文件,它没有asp页面的状态和生命周期,所以不能执行post回送的方法。
例如,在aspx页面里加一个TextBox和Button:
<asp:TextBox ID="txtTest" runat="server" Text="Hello" />
  
<asp:Button ID="btnsubmit" Text="改变TextBox文本" runat="server" OnClick="submit" />
在代码文件里:
protected void submit(object sender, EventArgs e)
{
txtTest.Text = "World";
}
很简单,就是按下这个按钮使TextBox的文本变成World,但是你会发现没有效果,TextBox里总是Hello。因为这个访问的不是aspx页面,而是
http://localhost:51927/eav
的形式。
最后:asp.net mvc强烈推荐Razor引擎,本文只是介绍一种方法,在mvc里装个web窗体也是没办法的事情。