Asp.net MVC实例第一步

1.首先创建一个mvc项目


点击确定


选择一个空的模板,勾选MVC


那么一个基本的mvc项目已经创建

此时可以点击Debug进行调试,但是会出现如下界面


因为此时还没有创建任何控制器和视图

添加控制器


点击添加后给控制器命名为HomeController

打开Home控制器,发现里面有一个已经生成的默认的Index的返回视图

创建index视图有两种方式:

第一种:直接在controller中的index上右键选择添加视图即可


第二种:在Views文件下的刚刚生成的Home文件夹下右键创建视图,选择empty即可

不添加布局页。

在创建好的index视图页中有

@{
    Layout = null;

}

这是一个简单的Razor引擎表达式,这代表未使用布局页。

这个地方介绍一下渲染和呈现


下面通过Razor表达式的ViewBag来接收一些信息

首先是HomeController里面

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

        }

然后在index的视图页中的div标签中添加

 @ViewBag.Greeting (from the view)

就可以看到效果了。

接下来创建一个模型GuestResponse


在类中定义一些属性及其get、set方法

 public class GuestResponse
    {
        public string Name { get; set; }
        public string Email { get; set; }     
        public string Phone { get; set; }
        public bool? WillAttend { get; set; }//willattend可为空

    }

2.表单验证及跳转

首先创建一个承载表单的视图RSVP,这是一个强类型视图


@model WebApplication1.Models.GuestResponse

在创建好的强类型视图中会有如上一个Razor表达式。这代表强类型视图。

然后我们先在index页面添加上一个跳转到此页面的链接

    <div>
        @Html.ActionLink("RSVP Now", "Rsvp")
    </div>

    第一个参数是要跳转链接所呈现的文本,可自行定义,第二个参数是跳转页面所调用的函数

此时还未创建。

在HomeController里面创建Rsvp返回视图页面的函数

 public ActionResult RSVP()
        {
            return View();

        }

在RSVP页面创建一个表单


<div >  
        <div >
            @using (Html.BeginForm())//Razor表达式
            {//s使用HTML辅助器从@model中读取所需信息     
                            <p>姓名:@Html.TextBoxFor(x => x.Name)</p>//lamda表达式
                                        <p>邮箱:@Html.TextBoxFor(x => x.Email)</p>
                                        <p>电话:@Html.TextBoxFor(x => x.Phone)</p>
                                        <p>
                                            Will you attend?
                                            @Html.DropDownListFor(x => x.WillAttend, new[]
    {
       new SelectListItem() {Text = "Yes,I'll be there",Value = bool.TrueString },
       new SelectListItem() {Text = "No,I can't come",Value = bool.FalseString }
    }, "选择一个")
                                        </p>

                                        <input type="submit" value="Submit Rsvp" />//此时单击只会清楚表单中已经输入的值,这是因为该表单会回递给home控制器中RsvpForm动作方法,这只是告诉MVC再次渲染该视图


             }
        </div>

    </div>

在模型中添加验证

 public class GuestResponse
    {
        [Required(ErrorMessage ="请输入你的姓名")]
        public string Name { get; set; }
        [Required(ErrorMessage ="请输入邮箱")]
        [RegularExpression(".+\\@.+\\..+", ErrorMessage = "输入的邮箱格式不正确")]
        public string Email { get; set; }
        [Required(ErrorMessage ="请输入电话号码")]
        public string Phone { get; set;}
        [Required(ErrorMessage ="请输入你是否想参加")]
        public bool? WillAttend { get; set; }//willattend可为空
    }

对于每次点击提交重新渲染视图的问题采用一种类似重载的方式来解决

[HttpGet]
        public ActionResult RsvpForm()
        {         
            return View();
        }
        [HttpPost]
        public ActionResult RsvpForm(GuestResponse gp)
        {
            if (ModelState.IsValid)
            {
                return View("Thanks", gp);
            }
            else
            { 
                return View();
            }

        }

可以看到两者的主要区别在于响应HTTP的方式

一种为get,一种为post,get请求是在点击一个链接时,浏览器正常发出的请求,当第一次访问RSVP中的表单时,正常显示为空白的表单;而当用HTML.BeginForm()渲染表达时,所默认的情况下是 post请求提交  。

Thanks视图页面代码

<div >
        <h1>Thank you, @Model.Name!</h1>
        <div >
            @if (Model.WillAttend == true)
            {
                @:It's great that you're coming.The drinks are already in the fridge!
            }
            else
            {
                @:Sorry to hear that you can't make it, but thanks for letting us know.
             }
        </div>

    </div>

RSVP界面需要添加一个行代码用于返回表单验证的提示信息

 @using (Html.BeginForm())//Razor表达式
            {//s使用HTML辅助器从@model中读取所需信息
                @Html.ValidationSummary()//返回验证消息的未排序列表

3.添加样式表

首先选中项目右键选择添加新文件夹,命名为Content

然后再Content上右键添加样式表Styles.css

再样式表中添加样式

.field-validation-error{color:#f00;}
.field-validation-valid{display:none;}
.input-validation-error{border:1px solid #f00;background-color:#fee;}
.validation-summary-errors{font-weight:bold;color:#f00;}
.validation-summary-valid{display:none;}

再RSVP页面引用改样式

<link rel="stylesheet" type="text/css" href="~/Content/Styles.css" />

这个样式仅仅是给验证信息提示时更加显眼一些,下面使用bootstrap库文件来修饰界面,可以在网站上直接下载改文件,也可使用NuGet来下载,它有一个特性是可以管理各个包之间的依赖项。


添加样式后index界面:

<head>
    <meta name="viewport" content="width=device-width" />
    <link href="~/Content/bootstrap.css"rel="stylesheet"/>
    <link href="~/Content/bootstrap-theme.css"rel="stylesheet"/>
    <style>
        .btn a{color:white;text-decoration:none}
        body{background-color:#F1F1F1;}
    </style>
    <title>Index</title>
</head>
<body>
    <div class="text-center"> 
        @ViewBag.Greeting (from the view)
        <h2>We're going to have an exciting party.<br />
        (To do:sell it better.Add pictures or something)</h2>
        <div class="btn btn-success">       
            @Html.ActionLink("RSVP Now", "RsvpForm")
        </div>
    </div>

</body>

Rsvp界面:

<head>
    <meta name="viewport" content="width=device-width" />
    <link rel="stylesheet" type="text/css" href="~/Content/CSS/Styles.css" />
    <link href="~/Content/bootstrap.css" rel="stylesheet" />
    <link href="~/Content/bootstrap-theme.css" rel="stylesheet" />
    <title>RsvpForm</title>
</head>
<body>
    <div class="panel panel-success">
        <div class="panel panel-heading text-center"><h4>RSVP</h4></div>
        <div class="panel-body text-center">
            @using (Html.BeginForm())//Razor表达式
            {//s使用HTML辅助器从@model中读取所需信息
                @Html.ValidationSummary()//返回验证消息的未排序列表
                <div class="form-group">
                    <label>姓名:</label>@Html.TextBoxFor(x => x.Name, new { @class = "formcontrol" })
                </div>
                <div class="form-group">
                    <label>邮箱:</label>@Html.TextBoxFor(x => x.Email, new { @class = "formcontrol" })
                </div>
                <div class="form-group">
                    <label>电话:</label>@Html.TextBoxFor(x => x.Phone, new { @class = "formcontrol" })
                </div>
                <div class="form-group">
                    <label>意愿:</label>@Html.DropDownListFor(x => x.WillAttend, new[] {
                        new SelectListItem() {Text = "Yes,I'll be there",Value = bool.TrueString },
                        new SelectListItem() {Text = "No,I can't come",Value = bool.FalseString }
                        }, "选择一个", new { @class = "formcontrol" })
                </div>
                <div class="text-center">
                    <input class="btn btn-success" type="submit" value="Submit RSVP" />
                </div>
            }
        </div>
    </div>

</body>

Thanks界面:

<head>
    <meta name="viewport" content="width=device-width" />
    <link href="~/Content/bootstrap.css" rel="stylesheet" />
    <link href="~/Content/bootstrap-theme.css" rel="stylesheet" />
    <style>
        body {
            background-color: #F1F1F1;
        }
    </style>
    <title>Thanks</title>
</head>
<body>
    <div class="text-center">
        <h1>Thank you, @Model.Name!</h1>
        <div class="lead">
            @if (Model.WillAttend == true)
            {
                @:It's great that you're coming.The drinks are already in the fridge!
            }
            else
            {
                @:Sorry to hear that you can't make it, but thanks for letting us know.
             }
        </div>
    </div>
</body>

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雨中深巷的油纸伞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值