你的位置:首页 > ASP.net教程

[ASP.net教程]小试ASP.NET MVC


上篇博客我们大体介绍了ASP.NET MVC以及如何去新建项目,这篇博客我们讲点干货。小试ASP.NET MVC,我们来写一个简单的邀请WEB。

首先,自然是首页,我们让其显示一个问候并邀请访问者的文字。

我们在Controller里面新建HomeController.cs文件,并在其Index方法中写如下代码。

    public ViewResult Index()    {      int hour = DateTime.Now.Hour;      ViewBag.Greeting = hour < 12 ? "Good Morning" : "Good Afternoon";       return View();    }

  接下来,当然是渲染Index界面了,我们新建一个Index视图文件,并在里面填充以下代码。(代码中使用了bootstrap框架,但这里不进行讲解,想了解的童鞋自行利用搜索引擎)

<html><head>  <meta name="viewport" content="width=device-width" />  <link href="~/Content/bootstrap.css" rel="stylesheet" />  <link href="~/Content/bootstrap-theme.css" rel="stylesheet" />  <title>Index</title>  <style>    .btn a {      color: black;      text-decoration:none    }    body {      background-color: #F1F1F2;    }  </style></head><body>  <div class="panel-body text-center"><h4>@ViewBag.Greeting</h4></div>  <div class="text-center">    <h2>We're going to have an exciting party!</h2>    <h3>And you are invited</h3>    <div class="btn btn-success">      @Html.ActionLink("PSVP Now", "RsvpForm")    </div>  </div></body></html>

 接下来我们运行项目,就会看见如下界面。

可是一个网站当然不会只有邀请信息这一个页面。接下来我们需要跳转到另外一个页面。在HomeController写一个RsvpForm方法,并渲染RsvpForm视图。

    public ViewResult RsvpForm()    {      return View();    }

  接着写RsvpForm视图。

<html><head>  <link href="~/Content/bootstrap.css" rel="stylesheet" />  <link href="~/Content/bootstrap-theme.css" rel="stylesheet" />  <meta name="viewport" content="width=device-width" />  <link href="~/Content/Styles.css" rel="stylesheet" />  <title>RsvpForm</title></head><body>  <div >    <div ><h4>RSVP</h4></div>    <div >      @using (Html.BeginForm())      {        @Html.ValidationSummary()        <div >          <label>Your name:</label>          @Html.TextBoxFor(x => x.Name, new { @class = "form-control" })        </div>        <div >          <label>Your email:</label>          @Html.TextBoxFor(x => x.Email, new { @class = "form-control" })        </div>        <div >          <label>Your phone:</label>          @Html.TextBoxFor(x => x.Phone, new { @class = "form-control" })        </div>        <div >          <label>Will you attend?</label>          @Html.DropDownListFor(x => x.WillAttend, new[]        {          new SelectListItem() { Text = "Yes, I'll be there.",Value = Boolean.TrueString},          new SelectListItem() { Text = "No, I can't come.",Value = Boolean.FalseString}        }, "Choose an option", new { @class = "form-control" })        </div>        <div >          <input type="submit" value="Submit RSVP"/>        </div>      }    </div>  </div></body></html>

  运行项目,我们会发现当点击PSVP Now按钮时,会跳转到这个界面。