zoukankan      html  css  js  c++  java
  • MVC3CRUDDemo(二)

    Controller:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using MVC3CRUDDemo.Models;
    using System.Data;
    
    namespace Mvc3DBCRUDDemo.Controllers
    {
        public class PeopleController : Controller
        {
            #region Variable
    
            private PeopleModels pModel;
    
            #endregion Variable
    
            #region Actions
            //
            // GET: /People/
    
            public ActionResult Index()
            {
                return View();
            }
    
            public ActionResult Create()
            {
                return View();
            }
    
            //重载方法
            [HttpPost]
            public ActionResult Create(PeopleModels people)
            {
                pModel = people;
                ViewBag.CreateResult = this.CreateData();
    
                //接受并存贮来自View的值
                ViewBag.Name = people.Name;
                ViewBag.Age = people.Age;
                ViewBag.Sex = people.Sex;
                ViewBag.BirthDate = people.BorthDate;
                ViewBag.BirthPlace = people.BorthPlace;
    
    
                //通过HttpPost方式传值,View中这样赋值 @Request.QueryString["key"]=value;
                //ViewBag.Name = Request.QueryString["key"];
    
                //错误的写法,Request.QueryString[]是只读的,不能对其赋值
                //Request.QueryString["Sex"] = people.Name;
                ViewBag.Sex = Request.QueryString["Age"];
    
                return View(people);
            }
    
            //public ActionResult Read()
            //{
            //    return View();
            //}
    
            public ActionResult Read()
            {
                DataTable table = this.ReadAll();
                List<PeopleModels> pModelList = new List<PeopleModels>();
                pModel = new PeopleModels();
                foreach (DataRow row in table.Rows)
                {
                    pModel.ID = int.Parse(row["ID"].ToString());
                    pModel.Name = row["Name"].ToString();
                    pModel.Sex = row["Sex"].ToString();
                    pModel.Age = int.Parse(row["Age"].ToString());
                    pModel.BorthDate = Convert.ToDateTime(row["BorthDate"].ToString());
                    pModel.BorthPlace = row["BorthPlace"].ToString();
                    pModelList.Add(pModel);
                }
    
                return View(pModelList);
            }
    
            public ActionResult Update()
            {
                return View();
            }
    
            /// <summary>
            /// Update data by ID
            /// </summary>
            /// <param name="id"></param>
            /// <returns></returns>
            public ActionResult Update(int id)
            {
                ViewBag.ID = Request.QueryString["id"].ToString();
                return View();
            }
    
            public ActionResult Delete()
            {
                return View();
            }
    
            #endregion Actions
    
            #region Methods
    
            private string CreateData()
            {
                return pModel.Create();
            }
    
            private DataTable ReadAll()
            {
                pModel = new PeopleModels();
                return pModel.ReadAll();
            }
    
            private void UpdateById()
            {
    
            }
    
            #endregion Methods
        }
    }

    MVC3 View:

    People\Create.cs:

    @model MVC3CRUDDemo.Models.PeopleModels
    
    @{
        ViewBag.Title = "CrateDemo";
    }
    
    <h2>Create Demo</h2>
    
    
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
    <script type="text/javascript">
    //        $(function()
    //        {
    //            document.getElementById("create").onclick = showMsg;
    //        })
    
    //        function showMsg(event)
    //        {
    //            alert("!!!");
    //        } 
    
    //    $("submit").click(function () {
    //        alert("good");
    //        });
    
    //    function create() {
    //        alert(@ViewBag.CreateResult);
    //}
    </script>
    
    <div id="ShowPeopleData">
    
    </div>
    
    <div id="CreatePeople">
    @using (Html.BeginForm()) {
        @Html.ValidationSummary(true, "Password change was unsuccessful. Please correct the errors and try again.")
        <div>
            <fieldset>
                <legend>People Information</legend>
                <div class="editor-label">
                    @Html.LabelFor(m => m.Name) : 
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.Name)
                    @Html.ValidationMessageFor(model => model.Name)
                </div>
    
                <div class="editor-label">
                    @Html.LabelFor(m => m.Sex)
                </div>
                <div class="editor-field">
                @{
                    List<SelectListItem> list = new List<SelectListItem>();
    
                    //TODO: Meet an issue when set [Range(typeof(string),"男","女")] for property Sex.
                    //list.Add(new SelectListItem { Text = "请选择", Value = "-1", Selected = true });
                    Mvc3DBCRUDDemo.Common.AgeType ageType = new Mvc3DBCRUDDemo.Common.AgeType();
                    foreach(string item in ageType.items)
                    {
                        list.Add(new SelectListItem { Text = item, Value = item});
                    }
                }
    
                @Html.DropDownListFor(model => model.Sex, list)
                @Html.ValidationMessageFor(model => model.Sex)
    
    
    
                 @*   @Html.DropDownListFor(m => m.Sex)
                    @Html.ValidationMessageFor(model => model.Sex)
    
    
                    @Html.RadioButton("reviewPassed", "通过",
          model => model.Sex == null ? false : model => model.Sex == 1
                , new { Style = "35px", disabled = "disabled" })<label>通过 </label>
                    @Html.RadioButton("reviewPassed", "不通过"
         , Model.Demand.Result == null ? false : model => model.Sex != 1
                , new { Style = "35px", disabled = "disabled" })<label>不通过 </label>*@
    
                </div>
    
                <div class="editor-label">
                    @Html.LabelFor(m => m.Age)
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.Age)
                    @Html.ValidationMessageFor(model => model.Age)
                </div>
    
                <div class="editor-label">
                    @Html.LabelFor(m => m.BorthDate)
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(model => model.BorthDate, new { @class = "date", id = "txtBorthDate" })
                    @Html.ValidationMessageFor(model => model.BorthDate)
    
    
                </div>
                <div class="editor-label">
                    @Html.LabelFor(m => m.BorthPlace)
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.BorthPlace)
                    @Html.ValidationMessageFor(model => model.BorthPlace)
                    </div>
                <p>
                    <input id="create" type="submit" value="Create"/>
                </p>
                <p style=" font:red" >@ViewBag.CreateResult</p>
            </fieldset>
        </div>
        }
    
        </div>

    People\Read.cs

    @model List<MVC3CRUDDemo.Models.PeopleModels>
    @{
        ViewBag.Title = "Read";
    }
    
    <h2>Read</h2>
    
    
    
    <p>WebGrid Demo</p>
    
    <div id="grid">
    @{ 
        var grid = new WebGrid(source: Model,
    defaultSort: "ID", 
    rowsPerPage: 10);
    }
    @grid.GetHtml(
    tableStyle: "grid",
    headerStyle: "head",
    alternatingRowStyle: "alt",
    columns: grid.Columns(
    grid.Column(format: (item) => Html.ActionLink("Update", "People", new { id = item.ID })),
    grid.Column(format: (item) => Html.ActionLink("Delete", "People", null, new { onclick = string.Format("deleteRecord('People', '{0}')", item.ID), @class = "Delete", href = "JavaScript:void(0)" })), 
    grid.Column("Name","姓名"),
    grid.Column("Sex","性别"),
    grid.Column("Age","年纪"),
    grid.Column("BorthDate", "出生日期"),
    grid.Column("BorthPlace","出生地点")
    )
    )
    </div>

    People\Update:

    @model MVC3CRUDDemo.Models.PeopleModels
    @{
        ViewBag.Title = "Update";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    <h2>Update</h2>
    
    
    <div id="UpdatePeople">
    @using (Html.BeginForm()) {
        @Html.ValidationSummary(true, "Password change was unsuccessful. Please correct the errors and try again.")
        <div>
            <fieldset>
                <legend>People Information</legend>
                <div class="editor-label">
                    @Html.LabelFor(m => m.Name) : 
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.Name)
                    @Html.ValidationMessageFor(model => model.Name)
                </div>
    
                <div class="editor-label">
                    @Html.LabelFor(m => m.Sex)
                </div>
                <div class="editor-field">
                @{
                    List<SelectListItem> list = new List<SelectListItem>();
    
                    //TODO: Meet an issue when set [Range(typeof(string),"男","女")] for property Sex.
                    //list.Add(new SelectListItem { Text = "请选择", Value = "-1", Selected = true });
                    Mvc3DBCRUDDemo.Common.AgeType ageType = new Mvc3DBCRUDDemo.Common.AgeType();
                    foreach(string item in ageType.items)
                    {
                        list.Add(new SelectListItem { Text = item, Value = item});
                    }
                }
    
                @Html.DropDownListFor(model => model.Sex, list)
                @Html.ValidationMessageFor(model => model.Sex)
    
    
    
                 @*   @Html.DropDownListFor(m => m.Sex)
                    @Html.ValidationMessageFor(model => model.Sex)
    
    
                    @Html.RadioButton("reviewPassed", "通过",
          model => model.Sex == null ? false : model => model.Sex == 1
                , new { Style = "35px", disabled = "disabled" })<label>通过 </label>
                    @Html.RadioButton("reviewPassed", "不通过"
         , Model.Demand.Result == null ? false : model => model.Sex != 1
                , new { Style = "35px", disabled = "disabled" })<label>不通过 </label>*@
    
                </div>
    
                <div class="editor-label">
                    @Html.LabelFor(m => m.Age)
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.Age)
                    @Html.ValidationMessageFor(model => model.Age)
                </div>
    
                <div class="editor-label">
                    @Html.LabelFor(m => m.BorthDate)
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(model => model.BorthDate, new { @class = "date", id = "txtBorthDate" })
                    @Html.ValidationMessageFor(model => model.BorthDate)
    
    
                </div>
                <div class="editor-label">
                    @Html.LabelFor(m => m.BorthPlace)
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.BorthPlace)
                    @Html.ValidationMessageFor(model => model.BorthPlace)
                    </div>
                <p>
                    <input id="create" type="submit" value="Create"/>
                </p>
                <p style=" font:red" >@ViewBag.CreateResult</p>
            </fieldset>
        </div>
        }
    
        </div>

    People\Delete.cs

    @{
        ViewBag.Title = "Delete";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    <h2>Delete</h2>

     DateExpressionAttribute.cs:

    using System.ComponentModel.DataAnnotations;
    using System.Web.Mvc;
    using System.Collections.Generic;
    using System;
    using System.Globalization;
    public class DateExpressionAttribute : RegularExpressionAttribute, IClientValidatable
    {
        public DateExpressionAttribute()
            : base(@"((^((1[8-9]\d{2})|([2-9]\d{3}))([-\/\._])(10|12|0?[13578])([-\/\._])(3[01]|[12][0-9]|0?[1-9])$)|(^((1[8-9]\d{2})|([2-9]\d{3}))([-\/\._])(11|0?[469])([-\/\._])(30|[12][0-9]|0?[1-9])$)|(^((1[8-9]\d{2})|([2-9]\d{3}))([-\/\._])(0?2)([-\/\._])(2[0-8]|1[0-9]|0?[1-9])$)|(^([2468][048]00)([-\/\._])(0?2)([-\/\._])(29)$)|(^([3579][26]00)([-\/\._])(0?2)([-\/\._])(29)$)|(^([1][89][0][48])([-\/\._])(0?2)([-\/\._])(29)$)|(^([2-9][0-9][0][48])([-\/\._])(0?2)([-\/\._])(29)$)|(^([1][89][2468][048])([-\/\._])(0?2)([-\/\._])(29)$)|(^([2-9][0-9][2468][048])([-\/\._])(0?2)([-\/\._])(29)$)|(^([1][89][13579][26])([-\/\._])(0?2)([-\/\._])(29)$)|(^([2-9][0-9][13579][26])([-\/\._])(0?2)([-\/\._])(29)$))")
        {
    
        }
    
        public override bool IsValid(object value)
        {
            return true;
        }
    
        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentCulture,
              "The filed {0} should be a date", name);
        }
    
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var name = metadata.GetDisplayName();
            var rule = new ModelClientValidationRegexRule(FormatErrorMessage(name), Pattern);
            yield return rule;
        }
    }
  • 相关阅读:
    Java 的 多态和构造方法
    java 的 抽象类、接口
    java 的 封装 、继承
    eclipse的安装和基本使用、面向对象、类和对象
    方法的重载、引用数据类型、 ArrayList集合
    SQL单行函数
    JAVA
    mysql约束
    MYSQL的常用属性
    mysql的索引
  • 原文地址:https://www.cnblogs.com/8090sns/p/MVC3CRUDDemo2.html
Copyright © 2011-2022 走看看