学习ASP.NET MVC 4之一(Pro ASP.NET MVC 4)

HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PartyInvites.Controllers {
    public class HomeController : Controller {

        public string Index() {
            return "Hello World";
        }
    }
}

按照原文的解释就是:“We have changed the action method called Index so that it returns the string ‘Hello, world‘.”

直接将字符串返回到页面,未通过任何模板页。

HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace PartyInvites.Controllers {
    public class HomeController : Controller {

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

"Return a ViewResult object from an action method, we are instructing MVC to render a view. (The View method with no parameters)

Index.cshtml

@{
        Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        Hello World (from the view)
    </div>
</body>
</html>

@{
        Layout = null;
}

This is an expression that will be interpreted by the Razor view engine.

It just tells Razor that we chose not to use a master page.

HomeController.cs

@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        @ViewBag.Greeting World (from the view)
    </div>
</body>
</html>

Index.cshtml

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PartyInvites.Controllers {
    public class HomeController : Controller {

        public ViewResult Index() {

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

 This is about Adding Dynamic Output.

GuestResponse.cs  Add a new Model Class

namespace PartyInvites.Models {
    public class GuestResponse {
        public string Name { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public bool? WillAttend { get; set; }
    }
}

Index.cshtml

@{
        Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        @ViewBag.Greeting World (from the view)
        <p>We‘re going to have an exciting party.<br />
        (To do: sell it better. Add pictures or something.)
        </p>
        @Html.ActionLink("RSVP Now", "RsvpForm")
    </div>
</body>
</html>

HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PartyInvites.Controllers {
    public class HomeController : Controller {

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

RsvpForm.cshtml

@model PartyInvites.Models.GuestResponse

@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>RsvpForm</title>
</head>
<body>
    @using (Html.BeginForm()) {
        <p>Your name: @Html.TextBoxFor(x => x.Name) </p>
        <p>Your email: @Html.TextBoxFor(x => x.Email)</p>
        <p>Your phone: @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}
            }, "Choose an option")
        </p>
        <input type="submit" value="Submit RSVP" />
    }
</body>
</html>

Handling Forms ( GET OR POST)

HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PartyInvites.Models;

namespace PartyInvites.Controllers {
    public class HomeController : Controller {

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

        [HttpGet]
        public ViewResult RsvpForm() {
            return View();
        }

        [HttpPost]
        public ViewResult RsvpForm(GuestResponse guestResponse) {
            // TODO: Email response to the party organizer
            return View("Thanks", guestResponse);
        }
    }
}

Thanks.cshtml

@model PartyInvites.Models.GuestResponse

@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Thanks</title>
</head>
<body>
    <div>
        <h1>Thank you, @Model.Name!</h1>
        @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>
</body>
</html>

About Validation

GuestResponse.cs

using System.ComponentModel.DataAnnotations;

namespace PartyInvites.Models {

    public class GuestResponse {

        [Required(ErrorMessage = "Please enter your name")]
        public string Name { get; set; }

        [Required(ErrorMessage = "Please enter your email address")]
        [RegularExpression(".+\\@.+\\..+",
            ErrorMessage = "Please enter a valid email address")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Please enter your phone number")]
        public string Phone { get; set; }

        [Required(ErrorMessage = "Please specify whether you‘ll attend")]
        public bool WillAttend { get; set; }
    }
}

HomeController.cs

...
[HttpPost]
public ViewResult RsvpForm(GuestResponse guestResponse) {
    if (ModelState.IsValid) {
        // TODO: Email response to the party organizer
        return View("Thanks", guestResponse);
    } else {
        // there is a validation error
        return View();
    }
}
...

~/Content/Site.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;}

RsvpForm.cshtml

@model PartyInvites.Models.GuestResponse

@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <link rel="stylesheet" type="text/css" href="~/Content/Site.css" />
    <title>RsvpForm</title>
</head>
<body>
    @using (Html.BeginForm()) {
    @Html.ValidationSummary()
    <p>Your name: @Html.TextBoxFor(x => x.Name) </p>
    <p>Your email: @Html.TextBoxFor(x => x.Email)</p>
    <p>Your phone: @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}
            }, "Choose an option")
    </p>
    <input type="submit" value="Submit RSVP" />
}
</body>
</html>

About Sent Email Message

Thanks.cshtml

@model PartyInvites.Models.GuestResponse

@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Thanks</title>
</head>
<body>
    @{
        try {
            WebMail.SmtpServer = "smtp.example.com";
            WebMail.SmtpPort = 587;
            WebMail.EnableSsl = true;
            WebMail.UserName = "mySmtpUsername";
            WebMail.Password = "mySmtpPassword";
            WebMail.From = "[email protected]";
            WebMail.Send("[email protected]", "RSVP Notification",
                Model.Name + " is " + ((Model.WillAttend ?? false) ? "" : "not")
                + "attending");
        } catch (Exception) {
            @:<b>Sorry - we couldn‘t send the email to confirm your RSVP.</b>
        }
    }
    <div>
        <h1>Thank you, @Model.Name!</h1>
        @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>
</body>
</html>

注释待续...

时间: 2024-08-07 04:42:19

学习ASP.NET MVC 4之一(Pro ASP.NET MVC 4)的相关文章

Pro ASP.NET Core MVC 第6版 第一章

第一章 ASP.NET Core MVC 的前世今生 ASP.NET Core MVC 是一个微软公司开发的Web应用程序开发框架,它结合了MVC架构的高效性和简洁性,敏捷开发的思想和技术,和.NET 平台的最好的部分.在本章,我们将学习为什么微软创建ASP.NET Core MVC, 看看他和他的前辈的比较以及和其他类似框架的比较,最后,大概讲一下ASP.NET core MVC里面有什么新东西,还有本书中包括哪些内容. 了解ASP.NET Core MVC的历史 最开始的ASP.NET 诞生

Pro ASP.NET Core MVC 第6版 第二章(前半章)

目录 第二章 第一个MVC 应用程序 学习一个软件开发框架的最好方法是跳进他的内部并使用它.在本章,你将用ASP.NET Core MVC创建一个简单的数据登录应用.我将它一步一步地展示,以便你能看清楚怎样构建一个MVC 应用程序.为了让事情简单,我跳过了一些技术细节,但是不要担心,如果你是一个MVC的新手,你将会发现许多东西足够提起你的兴趣.因为我用的东西有些没做解释,所以我提供了一些参考以便你可以看到所有的细节的东西. 安装Visual Studio 要想根据本书实践的话,必须安装Visua

Pro ASP.NET MVC 4, 4th edition Reading note---Part(1) DI

What I learned from Pro ASP.NET MVC 4 book Open source of Asp.net MVC http://www.opensource.org/licenses/ms-pl.html 1. Introduce new trends of web development Node.js, Ruby on Rails, 2. Ninject 1) Ninject is used to de-couple classed, which known as

Pro ASP.NET Core MVC 6th 第三章

第三章 MVC 模式,项目和约定 在深入了解ASP.NET Core MVC的细节之前,我想确保您熟悉MVC设计模式背后的思路以及将其转换为ASP.NET Core MVC项目的方式. 您可能已经了解本章中讨论的一些想法和约定,特别是如果您已经完成了高级ASP.NET或C#开发. 如果没有,我鼓励你仔细阅读 - 深入地理解隐藏在MVC背后的东西可以帮助你在通读本书时更好地与MVC框架的功能联系起来. MVC的历史 模型视图控制器模式起源于20世纪70年代后期,来自施乐PARC的Smalltalk

[ASP.NET MVC 小牛之路]01 - 理解MVC模式--转载

PS:MVC出来很久了,工作上一直没机会用.出于兴趣,工作之余我将展开对MVC的深入学习,通过博文来记录所学所得,并希望能得到各位园友的斧正. 本文目录 理解一般意义上的MVC模式 MVC模式(Model-View-Controller)是软件工程中的一种软件架构模式,把软件系统分为以下三个基本部分: 模型(Model):模型用于封装与应用程序的业务逻辑相关的数据以及对数据的处理方法.“模型”有对数据直接访问的权力,例如对数据库的访问.“模型”不依赖“视图”和“控制器”,也就是说,模型不关心它会

ASP.NET MVC 随想录——开始使用ASP.NET Identity,初级篇(转)

ASP.NET MVC 随想录——开始使用ASP.NET Identity,初级篇 阅读目录 ASP.NET Identity 前世今生 建立 ASP.NET Identity 使用ASP.NET Identity ASP.NET Identity 其他API介绍 小节 在之前的文章中,我为大家介绍了OWIN和Katana,有了对它们的基本了解后,才能更好的去学习ASP.NET Identity,因为它已经对OWIN 有了良好的集成. 在这篇文章中,我主要关注ASP.NET Identity的建

ASP.NET MVC应用迁移到ASP.NET Core及其异同简介

ASP.NET Core是微软新推出支持跨平台.高性能.开源的开发框架,相比起原有的ASP.NET来说,ASP.NET Core更适合开发现代应用程序,如跨平台.Dorker的支持.集成现代前端开发框架(如npm.bower.gulp等等).另外相比ASP.NET它的性能更好,还内置了依赖注入等功能对开发方式进行了优化.但它们之间也有很多相同或相似的地方,如都使用C#进行开发.都提供了MVC.Entity Framework.Identity等组件来快速构建应用程序. 本文将通过迁移一个简单的A

【对比学习】koa.js、Gin与asp.net core——中间件

web框架中间件对比 编程语言都有所不同,各个语言解决同一类问题而设计的框架,确有共通之处,毕竟是解决同一类问题,面临的挑战大致相同,比如身份验证,api授权等等,鄙人对node.js,golang,.net core有所涉猎,对各自的web框架进行学习的过程中发现了确实有相似之处.下面即对node.js的koa.golang的gin与.net core的asp.net core三种不同的web后端框架的中间件做一个分析对比 Node-Koa.js 应用级中间件 //如果不写next,就不会向下

ASP.NET Core: Getting Started with ASP.NET MVC Core(一)

1. ASP.NET Core the Unified Framework ASP.NET Core的统一框架 2. New Solution Project 新的解决方案项目 src folder: contains all projects that contain source code that make up your application. Program.cs: this file contains the Main method of an ASP.NET Core RC2 a

MVC系列学习(四)-初识Asp.NetMVC框架

注:本文章从伯乐那盗了两张图,和一些文字: 1.MVC设计模式 与 Asp.Net Mvc框架 a.MVC设计模式 MVC设计模式 是一种 软件设计模式,将业务逻辑 与 界面显示 分离,并通过某种方式 灵活改变代码设计方式. 它的优点是,降低了 页面呈现 和 后台业务的 耦合度. b.Asp.Net Mvc框架 它是微软 基于 MVC设计模式开发的一套 新的 Web机制. 传统的MVC设计模式,通过配置文件的方式,来决定控制器访问Model和视图 . 微软采用了一种"约定大于配置"的理