鍍金池/ 教程/ C#/ ASP.Net MVC模型綁定
ASP.Net MVC簡介
ASP.Net MVC過濾器
ASP.Net MVC視圖
ASP.Net MVC安全
ASP.Net MVC手腳架
ASP.Net MVC控制器
ASP.Net MVC與SQL Server數(shù)據(jù)庫操作
ASP.Net MVC NuGet包管理
ASP.Net MVC入門程序
ASP.Net MVC Razor
ASP.Net MVC Bootstrap
ASP.Net MVC單元測試
ASP.Net MVC動作
ASP.Net MVC模式
ASP.Net MVC選擇器
ASP.Net MVC開發(fā)環(huán)境配置
ASP.Net MVC生命周期
ASP.Net MVC模型綁定
ASP.Net MVC自托管(本地主機部署)
ASP.Net MVC驗證
ASP.Net MVC緩存
ASP.Net MVC數(shù)據(jù)模型
ASP.Net MVC路由
ASP.Net MVC教程
ASP.Net MVC助手
ASP.Net MVC數(shù)據(jù)注解
ASP.Net MVC Web API

ASP.Net MVC模型綁定

ASP.NET MVC模型綁定允許您將HTTP請求數(shù)據(jù)與模型進行映射。 這是使用HTTP請求中的瀏覽器發(fā)送的數(shù)據(jù)創(chuàng)建.NET對象的過程。對于ASP.Net MVC而言,ASP.NET Web Forms開發(fā)人員大多都感到困惑,因為視圖的值在到達控制類的動作方法時會如何轉(zhuǎn)換為Model類,這個轉(zhuǎn)換由模型綁定器完成。

模型綁定是HTTP請求和 C# 操作方法之間的良好設(shè)計橋梁。 它使開發(fā)人員可以方便地使用表單(視圖)上的數(shù)據(jù),因為POSTGET會自動傳輸?shù)街付ǖ臄?shù)據(jù)模型中。 ASP.NET MVC使用默認(rèn)的綁定器來完成這個場景。

我們來看一個簡單的例子,在上一章的項目中添加一個“創(chuàng)建視圖”,我們將看到如何從視圖中獲取這些值傳到EmployeeController動作方法。

以下是POST的創(chuàng)建動作方法。

// POST: Employee/Create
[HttpPost]
public ActionResult Create(FormCollection collection){
   try{
      // TODO: Add insert logic here
      return RedirectToAction("Index");
   }catch{
      return View();
   }
}

右鍵單擊Create動作方法,然后選擇添加視圖…, 它將顯示添加視圖對話框。
如在上面的屏幕截圖中看到的那樣,默認(rèn)的動作名字已經(jīng)在輸入框中了?,F(xiàn)在從“模板”下拉列表中選擇“Create”,從“模型”下拉列表中選擇“Employee”。參考下圖 -

創(chuàng)建的Create.cshtml 視圖中看到默認(rèn)代碼如下 -

@model MVCSimpleApp.Models.Employee

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Create</title>
</head>
<body>
    @using (Html.BeginForm()) 
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <h4>Employee</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.JoiningDate, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.JoiningDate, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.JoiningDate, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }

    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>

當(dāng)用戶在創(chuàng)建視圖上輸入值時,它在FormCollectionRequest.Form中都可用。可以使用這些值中的任何一個來填充視圖中的員工信息。

使用下面的代碼來(FormCollection)創(chuàng)建員工信息。參考以下代碼 -

// POST: Employee/Create
[HttpPost]
public ActionResult Create(FormCollection collection){
   try {
      Employee emp = new Employee();
      emp.Name = collection["Name"];
      DateTime jDate;
      DateTime.TryParse(collection["DOB"], out jDate);
      emp.JoiningDate = jDate;
      string age = collection["Age"];
      emp.Age = Int32.Parse(age);
      empList.Add(emp);
      return RedirectToAction("Index");
   }catch {
      return View();
   }
}

運行這個應(yīng)用程序并請問這個URL: http:// localhost:63004 / Employee /。將收到以下輸出結(jié)果 -

點擊頁面頂部的“Create New”鏈接,它將轉(zhuǎn)到下面的視圖。如下所示 -

輸入想要添加的其他員工的數(shù)據(jù)。如下所示 -

點擊創(chuàng)建按鈕,會看到新員工被添加到列表中。如下圖所示 -

在上面的示例中,從HTML視圖中獲取所有發(fā)布的值,然后將這些值映射到Employee屬性并逐一分配它們。

在這種情況下,我們也將在發(fā)布的值與Model屬性的格式不相同的情況下進行類型轉(zhuǎn)換。

這也被稱為手動綁定,這種類型的實現(xiàn)對于簡單和小數(shù)據(jù)模型可能不是那么糟糕。 但是,如果對于具有大量的數(shù)據(jù)類型的模型,則需要大量的類型轉(zhuǎn)換,那么可以利用ASP.NET MVC Model綁定的強大功能和易用性。

下面來看看為模型綁定所做的另一個例子。

我們需要改變Create方法的參數(shù)來接受Employee模型對象而不是FormCollection對象,如下面的代碼所示。

// POST: Employee/Create
[HttpPost]
public ActionResult Create(Employee emp){
   try{
      empList.Add(emp);
      return RedirectToAction("Index");
   }catch{
      return View();
   }
}

現(xiàn)在,模型綁定的魔力取決于提供值的HTML變量的id

對于Employee模型,HTML輸入字段的id應(yīng)該與Employee模型的屬性名稱相同,可以看到Visual Studio在創(chuàng)建視圖時使用了相同的模型屬性名稱。如下代碼 -

@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })

映射將基于默認(rèn)的屬性名稱。在這里,您會發(fā)現(xiàn)HTML助手方法非常有用,因為這些助手方法將生成HTML,它將具有適當(dāng)?shù)拿Q以使模型綁定起作用。

運行修改代碼的應(yīng)用程序,與上面的運行結(jié)果一樣。