Asp.net MVC4 Step by Step (2)-参数数据的传递

首先创建一个表单,不同于WebForm,框架提供了一系列HMTL帮助方法来生成HTML标签。 下面创建一个Create.cshtml为文件名的视图。

<h2> Create Auction</h2>
@using (Html.BeginForm())
{
    <p>
        @Html.LabelFor(model => model.Title)
        @Html.EditorFor(model => model.Title)
 
    </p>
    <p>
        @Html.LabelFor(model => model.Description)
        @Html.EditorFor(model => model.Description)
    </p>
    <p>
        @Html.LabelFor(model => model.StartPrice)
        @Html.EditorFor(model => model.StartPrice)
    </p>
    <p>
        @Html.LabelFor(model => model.EndTime)
        @Html.EditorFor(model => model.EndTime)
    </p>
    <p>
        <input type="submit" value="Create" />
    </p> 
}

用户可以在这个页面表单中填写商品数据,提交给/auctions/create操作。 这个Create操作标记了HttpPostAttribute标记属性,用来告诉ASP.NETMVC框架,它是用来处理HTML表单的Post方式提交的操作方法。

传统要得到提交的数据,需要把数据从请求消息中提出来, MVC框架中,可以把模型当做操作的参数,比如已经创建了一个模型, Auction类, 为了绑定之前定义额Auction类, 在操作方法上把Auction模型作为参数类型,

        [HttpPost]
        public ActionResult Create(Auction auction)
        {
           //数据库操作
 
            return View(auction);
        }

Auction模型类的属性名(Title, Description等)要与Html表单中提交的域元素名一致。就是name元素吧。


保存数据到数据库

使用Entity Framework代码优先模式创建数据库访问层, 它的核心有赖于System.Data.Entity.DbContext类。 这个类是代码访问数据库的网关,提供了数据库相关的操作。

   using System.Data.Entity;
    public class EbuyDataContext:DbContext
    {
        public DbSet<Auction> Auctions { get; set; }
        public EbuyDataContext()
        {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<EbuyDataContext>());
        }
    
    }

在Auction.cs里, 我们创建了一个自定义的数据上下文类,名字是EbuyDataContext类, 这个类定义了一个属性System.Data.Entity.DbSet<T>, T 是编辑或保存到数据库的实体对象的类型, 这样System.Data.Entity.DbSet<Auction>就表示要保存Auction数据到数据库, 程序在运行的时候,如果没有相应数据库和表,就会新建库和表,然后写入数据。

image

 
        [HttpPost]
        public ActionResult Create(Auction auction)
        {
                var db = new EbuyDataContext();
                db.Auctions.Add(auction);
                db.SaveChanges();
            return View(auction);
        }

但是这样不加验证,就处理数据到数据库有风险,比如“ABC”保存到Int型的字段。 所以下一节讲的是怎么在服务端和客户端验证的问题。

原文地址:https://www.cnblogs.com/grkin/p/3301445.html