Mvc3提交表格验证

Model层:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace MvcApplication1.Models
{
    public class User
    {
        public int ID { get; set; }


        [DisplayName("姓名")]
        [Required(ErrorMessage = "姓名不能为空")]
        public string Name { get; set; }

        [DisplayName("密码")]
        [Required(ErrorMessage = "密码不及为空")]
        [RegularExpression(@"^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$", ErrorMessage = "请输入正确的Email格局\n示例:[email protected]")]      
        //[StringLength(10, MinimumLength = 6, ErrorMessage = "密码6-10位")]
        public string Password { get; set; }
    }
}

Control层:
using System.Web.Mvc;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class UserController : Controller
    {

        public ActionResult Create()
        {

            return View();

        }
        [HttpPost]
        public ActionResult Create(User model)
        {
            if (ModelState.IsValid)
            {
                var a = "";
            }
            return View(model);

        }
    }
}

UI层:
@model MvcApplication1.Models.User

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create</h2>
@using (Html.BeginForm()) {
    <div>
        <fieldset>
            <legend>Account Information</legend>

            <div class="editor-label">
                @Html.LabelFor(m => m.Name)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.Name)
                @Html.ValidationMessageFor(m => m.Name)
            </div>

            <div class="editor-label">
                @Html.LabelFor(m => m.Password)
            </div>
            <div class="editor-field">
             @Html.TextBoxFor(m => m.Password)
                @*@Html.PasswordFor(m => m.Password)*@
                @Html.ValidationMessageFor(m => m.Password)
            </div>

            <p>
                <input type="submit" value="Log Out" />
            </p>
        </fieldset>
    </div>
}

你可能感兴趣的:(mvc)