DIV CSS 佈局教程網

MVC 表單提交的四種做法完整解析
編輯:關於JavaScript     

在 ASP.NET MVC 裡,把表單資料送到 Controller 有幾條不同的路。本文整理四種常見做法,並說明各自的參數綁定規則。

總覽

  1. MVC HtmlHelper 方法(Html.BeginForm / BeginRouteForm)
  2. 傳統 HTML 表單的 action 屬性
  3. jQuery + Ajax 提交
  4. Controller 端的參數接收方式

一、Html.BeginForm()

Html.BeginForm(actionName, controllerName, method, htmlAttributes) { }

重點:所有要一起提交的內容(包含送出按鈕)都必須寫在大括號內。

主要參數:

  • actionName(String):操作方法名稱
  • controllerName(String):控制器名稱
  • routeValues(Object):路由參數,透過反射讀取屬性
  • method(FormMethod):GET 或 POST
  • htmlAttributes(Object):要套用的 HTML 屬性

回傳值型別為 System.Web.Mvc.Html.MvcForm,也就是 <form> 的開始標籤。

View 範例:

<h1>在線申請</h1>
@using (Html.BeginForm("Apply", "Star", FormMethod.Post, new { @class = "MyForm" })) {
  <div class="application_b_3">
    <table width="820" border="0">
      <tr>
        <td width="80" height="50">達人類型</td>
        <td width="730">
          @Html.DropDownListFor(m => m.StarModel.TypeID, Model.DropList,
                                new { id = "type", @class = "my-" })
        </td>
      </tr>
      <tr>
        <td height="50">首頁達人照</td>
        <td>
          <div class="picture_an" id="UploadPhoto" style="width: 142px">
            <a href="javascript:void(0);" class="btn_addPic">
              <span><em>+</em>上傳照片</span>
              <input tabindex="3" title="支持jpg、jpeg、gif、png格式,文件小於5M"
                     size="3" name="pic" id="absFileInput" class="filePrew" type="file" />
            </a>
          </div>
        </td>
      </tr>
      <tr>
        <td height="50"></td>
        <td>
          @Html.HiddenFor(m => m.StarModel.UserGravatar, new { id = "SXtPhoto" })
          <img src="" id="imgPhoto" height="176px" />
        </td>
      </tr>
      <tr>
        <td height="100">自薦理由</td>
        <td>
          @Html.TextAreaFor(m => m.StarModel.ApplyReason, new { id = "tDesc" })
        </td>
      </tr>
      <tr>
        <td height="50"></td>
        <td>
          <a href="javascript:void(0)" id="btnApplication">
            <img src="@Url.Content("~/Areas/SNS/Themes/Default/Content/images/ap_9.gif")" alt="" />
          </a>
        </td>
      </tr>
    </table>
  </div>
}

二、BeginRouteForm()

與 BeginForm 的差別是「以路由名稱產生 action」,而不是以控制器/方法名稱。

BeginRouteForm(routeName, routeValues, method)

參數含 routeName(用來取得表單 post URL 的路由名稱)、routeValues、method,回傳同樣是 MvcForm。

<div class="group-search-box clearfix">
@using (Html.BeginRouteForm("SearchPage", new {
    cityID = Model.CityID,
    productType = Model.CurrentProductType,
    currentPageIndex = Model.CurrentIndex,
    keyword = Model.keyword
  }, FormMethod.Get)) {
  <input type="text" name="keyword" class="search-ipt" value=@Model.keyword>
  <input type="submit" id="submit" value="搜 索" class="gsearch-btn">
}
</div>

搜尋表單常用 GET,參數會出現在網址上,方便分享與/bookmark。

三、傳統 form action 屬性

直接用 HTML 原生寫法,action 搭配 Url.Action() 產生網址:

<form id="askform" action="@Url.Action("AskForm")" method="post">
  <div class="title-area-outter clearfix">
    <span></span>
    <select id="dplBDTType" name="dplBDTType"></select>
    <select id="selType" name="selType"></select>
  </div>
</form>

四、jQuery + Ajax 提交

View 端只放一個觸發元素:

<div class="issue" id="postWeibo" style="width: 80px">
  <a href="javascript:void(0)" class="publish-btn">發布</a>
</div>

或用表單包起來:

<form id="dataform" action="UpdateUserInfo" enctype="multipart/form-data" method="post">
  <input type="text" name="nvc_name" id="nvc_name" value="@Model.nvc_name" />
  <input type="button" value="保存" id="btnsubmit" />
</form>

<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$('#btnsubmit').click(function () {
  if ($("[name='nvc_name']").val() == "") {
    alert("請填寫名字");
    $("[name='nvc_name']").focus();
    return;
  }
  $("#dataform").ajaxSubmit(function (r) {
    alert(r.Msg);
    if (r.success) { location.reload(); }
  });
});
</script>

Controller 端如何接收

1. 普通參數:HTML 標籤的 name 與方法參數同名即可對應。

public ActionResult AskForm(string txtTitle, string txtEditor,
                           string dplBDTType, string selType, string txtYZM)
{ }

2. 實體傳參:HTML 標籤的 name 要與 Model 屬性名稱一致,MVC 的 Model Binder 會自動對應。

[HttpPost]
public ActionResult Apply(ViewModel.SNS.Star model)
{
  // 邏輯
}

3. 表單集合傳參:直接收 FormCollection,適合欄位不固定或想手動處理的情況。

[HttpPost]
public ActionResult Apply(FormCollection form)
{
  // 邏輯
}

怎麼選

需要 strongly-typed、搭配驗證的表單,用 HtmlHelper 最省事;路由規則複雜時選 BeginRouteForm;只是單純幾個欄位,直接寫 HTML form 反而清爽;要局部更新、不希望整頁重載,就用 Ajax。

不論哪一種,POST 動作都別忘了在 Controller 上加 [ValidateAntiForgeryToken] 並在表單中輸出對應 token,以防 CSRF。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved