實際開發中最常回頭查的,往往就是「表單怎麼送出去」這種基本題。以下整理三種在 MVC 專案裡最常用的提交方式。
最傳統、也最不必額外套件的做法。按下 submit 後瀏覽器直接送出表單、整頁重載。
<form action="MyDemand" method="post"> <span>關鍵字:</span> <input name="keywords" type="text" value="@keywords" /> <input type="submit" value="搜索" /> </form>
適合搜尋這類「結果需要另開頁面呈現」的場景。注意 name 屬性一定要設,否則 Controller 收不到值。
使用 jQuery Form Plugin 的 ajaxSubmit(),可以保留表單結構的同時以非同步方式送出,包含檔案上傳(enctype="multipart/form-data")也支援。
<form id="dataform" action="UpdateUserInfo" enctype="multipart/form-data" method="post">
<table style="width:100%;border:0;" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td width="40">名字:</td>
<td><input type="text" name="nvc_name" id="nvc_name" value="@Model.nvc_name" /></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="button" value="保存" id="btnsubmit" />
</td>
</tr>
</tbody>
</table>
</form>
<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="https://malsup.github.io/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#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>
注意觸發用的是 type="button" 而非 submit,避免瀏覽器又跑一次原生提交造成重複送出。
表單欄位不多、或資料需要加工後才送,直接手動組物件最自由。
<table style="width:100%;border:0px;" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td width="15%" align="right">手機號:</td>
<td><input type="text" placeholder="請輸入手機號" id="nvc_user_name" /></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="button" value="保存" id="btnsubmit" />
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
$(function () {
$("#btnsubmit").click(function () {
var nvc_user_name = document.getElementById('nvc_user_name');
$.post('/Interface/ModefiyPwd', { nvc_user_name: nvc_user_name.value }, function (data) {
if (data.success) {
$("#successdiv").show();
$("#editdiv").hide();
} else {
layer.msg(data.Msg);
}
});
});
});
</script>
submit 適合整頁刷新流程;ajaxSubmit 適合「表單欄位多但不想離開頁面」;$.post 適合欄位少、需要前置加工或欄位來源不只是一個表單。
無論用哪一種,有幾件事值得養成習慣:
{ success: bool, Msg: string }),前端判斷才不會越寫越亂。async: false 硬把非同步改成同步,那會凍結整個 UI。