MVC Create

本文介绍如何在MVC里往数据库中插入新的记录。

这里用到的数据表如下:

Employees

Step 1:

在Control文件里加入method

        public ActionResult Create()
        {
            return View();
        }

Step 2:

创建View, 其中部分代码为:

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Employee</legend>

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

        <div class="editor-label">
            @Html.LabelFor(model => model.Gender)
        </div>
        <div class="editor-field">
            @Html.DropDownList("Gender", new List<SelectListItem> { 
       new SelectListItem{ Text = "Male", Value = "Male"},
       new SelectListItem{ Text = "Female", Value = "Female"}}, "Select Gender"  )
            @Html.ValidationMessageFor(model => model.Gender)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.City)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.City)
            @Html.ValidationMessageFor(model => model.City)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.DateOfBirth)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.DateOfBirth)
            @Html.ValidationMessageFor(model => model.DateOfBirth)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

Step 3: 创建HttpPost Method

        [HttpPost]
        public ActionResult Create(FormCollection formCollection)
        {
            foreach (var key in formCollection.AllKeys)
            {
                Response.Write("Key = " + key + "  value = " + formCollection[key]);
                Response.Write("<br />");
            }
            return View();
        }

通过FormCollection,我们可以获得用户输入的值。有了这些值,我们可以把它插入到数据表中。

我们还可以在这个method里直接把所要得到的值放在parameter list里,用户输入的数据会自动“绑定”到所对应的参数上。

还有一种更好的方法,就是直接把该方法的参数定义为Employee,

还有一种方法,根本不使用parameter, 而是通过UpdateModel方法。这种方法如下:

UpdateModel method inspects all the HttpRequest inputs such as posted Form data, QueryString, Cookies and Server variables and populate the employee object.

 

转载于:https://www.cnblogs.com/beiyeqingteng/p/4265118.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值