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.