1. 程式人生 > >ASP.NET MVC 的表單提交

ASP.NET MVC 的表單提交

       ASP.NET MVC 開發過程中,我們經常要提交表單資料到後臺進行處理。今天就把常見的開發過程中用到的一些資料(表單)提交的方式做一個總結,方便自己今後查閱,如果對大家有益,那就更好了,總結得不好請大家給我留言指正。

       首先我們說說不使用ASP.NET MVC 的一些特性,也不使用Jquery的Ajax做最簡單的表單提交。這種表單提交只使用了HTML標籤,使用html表單form的Action指向需要接收引數的Controllrt裡面的Action。這時候獲取表單裡面的引數是通過Request.Form的形式來獲取的。Request請求封裝了form表單的具體細節。這個例子的程式碼如下:

 1.控制器

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

[HttpPost]
public string Regist(string name)
{
     string username = Request.Form["Username"];
     string password = Request.Form["Password"];
     return "Welcome:" + name;
}

2.Regist.ashtml

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Regist</title>
    <script src="../../Scripts/jquery-1.4.4.js" type="text/javascript"></script>
    <script type="text/javascript">
        function Submit() {
            $("#frmRegist").submit();
        }
    </script>
</head>
<body>
    <div>
      <form id="frmRegist" action="/Home/Regist" method="post">
        <table border="2">
            <tr>
                <th colspan="2">User Regist</th>
            </tr>
            <tr>
                <td>Username:</td>
                <td><input type="text" id="txtUsername" name="Username" /></td>
            </tr>
            <tr>
                <td>Password:</td>
                <td><input type="password" id="txtPassword" /></td>
            </tr>
            <tr>
                <td colspan="2"><input type="button" id="btnSubmit" value="Regist" onclick="Submit()" /></td>
            </tr>
        </table>
       </form>
    </div>
</body>
</html>

這裡面我們僅僅使用了Jquery來獲取form物件而已,通過document.GetElementById也可以辦到,本質上來說還是可以不依賴Jquery的。

可以看到前端輸入的值從後臺的方法可以獲取到,再進行處理就很方便了。這是最原始的表單提交方式,缺點在於如果欄位很多的話,需要對每一個欄位進行獲取。

然後我們可以使用ASP.NET MVC 支援的模型繫結的form進行提交,模型繫結之後,我們就可以提交一個物件過去,這樣就方便多了。模型繫結的控制器如下:

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

[HttpPost]
public ActionResult Regist2(User user)
{
     return View();
}

注意,控制器這時候跟模型沒關係,繫結模型的頁面直接和模型打交道。

@model MyMvcApp.Models.User

@{
    Layout = null;
}

@using (Html.BeginForm("Regist2", "Home", FormMethod.Post))
{
    <p>name:@Html.TextBoxFor(x => x.Name)</p>
    <p>email:@Html.TextBoxFor(x => x.Email)</p>
    <p>phone:@Html.TextBoxFor(x => x.Phone)</p>
    <p>gender:@Html.DropDownListFor(x=>x.Gender,new []{ 
             new SelectListItem{ Text = "boy", Value = "male", Selected = true},
             new SelectListItem{ Text = "girl", Value = "female", Selected = false }},"--please select gender--")</p>
    <p><input type="submit" id="btnSubmit" value="submit" /></p>
}

這裡的模型繫結之後,輸入框等跟欄位就直接綁定了。執行效果如下:

接下來,我們再討論一種以Ajax形式提交的表單,就是AjaxForm,這種form是 html的一種擴充套件標籤。ajax提交不需要重新整理的特性增強了使用者體驗,不失為一種好方法。

控制器程式碼如下:

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

[HttpPost]
public string Regist3(User user)
{
     return "Welcome:" + user.Name;
}

頁面的程式碼如下:

@model MyMvcApp.Models.User
@{
    Layout = null;
}
<script src="../../Scripts/jquery-1.4.4.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
<script type="text/javascript">
    function OnSuccess(responseData) {
        $("#result").html = responseData;
    }
</script>
@using (Ajax.BeginForm("Regist3", "Home", null, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "result", OnSuccess = "OnSuccess" }))
{
    <p>NAME:@Html.TextBoxFor(x => x.Name)</p>
    <p>EMAIL:@Html.TextBoxFor(x => x.Email)</p>
    <p>PHONE:@Html.TextBoxFor(x => x.Phone)</p>
    <p><input type="submit" id="btnSubmit" value="submit" /></p>
}

<div id="result">

</div>


執行效果就是通過Ajax請求,返回一個歡迎使用者的字串。初始介面如下:



submit之後的介面:

最後介紹通過Ajax提交的表單形式,這種形式其實不侷限於表單,通常做資料的提交都可以做,這裡為了演示,使用了一個表單來做例子。控制器程式碼如下:

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

[HttpPost]
public string Regist4(string username,string email)
{
    return "Hello: [" + username + "] your eamil is : [" + email + "]";
}

頁面程式碼如下:

@{
    Layout = null;
}

<script src="../../Scripts/jquery-1.4.4.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#btnSubmit").click(function () {
            $.ajax({
                url: "/Home/Regist4",
                type: "POST",
                dataType: "JSON",
                data: { username: $("#txtName").val(), email: $("#txtEmail").val() },
                success: function (data) {
                    //alert(data);
                    $("#result").html("success");
                    $("#result").css("color", "red");
                }
            });
        });
    });
</script>
<table border="2">
    <tr>
        <td colspan="2" align="center">User Regis Demo</td>
    </tr>
    <tr>
        <td>NAME:</td>
        <td><input type="text" id="txtName" style="width:160"/></td>
    </tr>
    <tr>
        <td>Email:</td>
        <td><input type="text" id="txtEmail" style="width:160"/></td>
    </tr>
    <tr>
        <td><input type="reset" id="btnReset" value = "reset" style="width:50" /></td>
        <td><input type="submit" id="btnSubmit" value = "submit" style="width:160"/></td>
    </tr>
</table>
<div id="result">Jquery Ajax Call Result Will Display here...</div>


執行結果就是通過Ajax提交之後,返回結果,更新div裡面的內容。


這幾種形式的提交都是支援的,希望對大家有所幫助的。