Views\Home\Index.cshtml
@*通过Binder机制把表单Post的数据赋给参数对象对应的属性*@
@model MvcHelloWorld.Models.Person
@{
ViewBag.Title = "Index";
}
<div>
<h1>Please Input Your Information</h1>
@using (Html.BeginForm("SendInformation","Home"))
{
<p>@Html.ValidationSummary()</p>
<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>Gender:
@Html.DropDownListFor(x=>x.Gender,
new[]{
new SelectListItem(){Text="I am boy",Selected=true,Value="Male"},
new SelectListItem(){Text="I am girl",Selected=false,Value="Female"},
},"Please select your gender")</p>
<p><input type="submit" value="Submit Your Information"/></p>
}
</div>
Views\Home\Welcome.cshtml
@{
//显示当前页面的标题的
ViewBag.Title = "Welcome";
}
<h2>@ViewBag.name Welcome</h2>
Models\HomeModels.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
//验证必须应用该命名空间,在页面里添加@Html.ValidationSummary(),在Action里添加
//if(ModelState.IsValid)
//{
// return Content("Thank You," + person.Name + "," + person.Email + "," + person.Phone + "," + person.Gender);
//}
//else
//{
// return View("Index");
//}
using System.ComponentModel.DataAnnotations;
namespace MvcHelloWorld.Models
{
public class Person
{
[Required(ErrorMessage="Please enter your name")]
public string Name { get; set; }
[Required(ErrorMessage="Please enter your email address")]
public string Email { get; set; }
[Required(ErrorMessage=("Please enter your phone number"))]
public string Phone { get; set; }
[Required(ErrorMessage="Please select your gender")]
public string Gender { get; set; }
}
}
Controllers\HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcHelloWorld.Models;
namespace MvcHelloWorld.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
////系统默认请求被路由到HomeController和Index这个Action
//public string Index()
//{
// //直接写字符串到客户端,可以不用添加 Index.cshtml 页面
// return "<h2>Index action returns string ‘Hello world‘ directly</h2>";
//}
//返回非字符串, 需要添加 Welcome.cshtml
public ActionResult Welcome()
{
//ViewBag是Controller定义的一个动态类型的属性,意味着你可以给他添加任何属性,在编译时动态类型的属性是不检查的
//页面可通过 @ViewBag.XX 直接调用值
ViewBag.name = "Welcome action returns View to show ViewBag name";
return View();
}
public ActionResult SendInformation(Person person)
{
if(ModelState.IsValid)
{
return Content("Thank You," + person.Name + "," + person.Email + "," + person.Phone + "," + person.Gender);
}
else
{
return View("Index");
}
}
}
}