iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 27
2
Modern Web

ASP.NET MVC網頁程式介紹系列 第 27

[Day 27] 用ASP.NET MVC 做簡單的註冊及登入系統(三)

今天來完成註冊功能吧!

首先這是註冊頁面
https://ithelp.ithome.com.tw/upload/images/20180105/20105694Bq21C5ywxa.jpg

註冊完成之後進入登入頁面
https://ithelp.ithome.com.tw/upload/images/20180105/20105694wSYFcLvtlm.jpg

這是註冊頁面的前端

@{
    ViewBag.Title = "Home Page";
    Layout = null;

    var cityList = ViewBag.CityList;
    var villageList = ViewBag.VillageList;
}

@model MVCTest.Models.UserData

@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")

<form style="margin-left:10px;" method="post" action="">
    <h1>請輸入使用者資料</h1>
    <div>
        <span style="color:red">@ViewBag.Msg</span>
    </div>
    <div class="form-group">
        <label for="exampleInputEmail1">帳號</label>
        <input type="text" class="form-control" id="Account" name="account" placeholder="輸入帳號" value="@Model.account">
        <small id="emailHelp" class="form-text text-muted">請輸入英數字</small>
    </div>
    <div class="form-group">
        <label for="exampleInputPassword1">新的密碼</label>
        <input type="password" class="form-control" id="Password1" name="password1" placeholder="輸入密碼" value="">
    </div>
    <div class="form-group">
        <label for="exampleInputPassword1">再次確認</label>
        <input type="password" class="form-control" id="Password2" name="password2" placeholder="輸入密碼" value="">
    </div>
    <div class="form-group">
        <label for="Address">地址</label>
        <select id="city" name="city">
            <option value="">全部</option>
            @for(int i=0;i<cityList.Count;i++)
            {
                <option value="@cityList[i].CityId" @Html.Raw(Model.city == cityList[i].CityId ? "selected" : "")>@cityList[i].CityName</option>
            }
        </select>
        <select id="village" name="village">
            @if (villageList.Count == 0)
            {
                <option value="">請選擇縣市</option>
            }
            else
            {
                <option value="">請選擇</option>
                for (int i = 0; i < villageList.Count; i++)
                {
                    <option value="@villageList[i].VillageId" @Html.Raw(Model.village == villageList[i].VillageId ? "selected" : "")>@villageList[i].VillageName</option>
                }
            }
        </select>
        <input type="text" class="form-control" id="Address" name="address" placeholder="輸入地址" value="@Model.address">
    </div>
    <button type="submit" class="btn btn-primary">確定</button>
    <button type="reset" class="btn btn-warning">清除</button>
</form>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    $("#city").change(function () {
        var value = $("#city").val();
        console.log(value);
        $.ajax({
            type: "Post",
            url: "../Home/Village?id=" + value,
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            success: function (data) {
                $("#village").empty();
                if (data == "") {
                    $("#village").append("<option value=''>請選擇縣市</option>");
                }
                else {
                    var jo = JSON.parse(data);
                    $("#village").append("<option value=''>請選擇</option>");
                    for (i = 0; i < jo.length; i++) {
                        $("#village").append("<option value='" + jo[i].VillageId + "'>" + jo[i].VillageName + "</option>");
                    }
                }
            },
            failure: function (errMsg) {
                $("#village").empty();
                $("#village").append("<option value=''>請選擇縣市</option>");
            }
        })
    });
</script>

這是後端接收的部分跟登入頁面

[HttpPost]
public ActionResult Index(UserData data)
{
    if (string.IsNullOrWhiteSpace(data.password1) || data.password1 != data.password2)
    {
        List<City> cityList = db.GetCityList();
        List<Village> villageList = new List<Village>();
        if (!string.IsNullOrWhiteSpace(data.city))
            villageList = db.GetVillageList(data.city);
        ViewBag.CityList = cityList;
        ViewBag.VillageList = villageList;
        ViewBag.Msg = "密碼輸入錯誤";
        return View(data);
    }
    else
    {
        if (db.AddUserData(data))
        {
            Response.Redirect("~/Home/Login");
            return new EmptyResult();
        }
        else
        {
            ViewBag.Msg = "註冊失敗...";
            return View(data);
        }
    }
}

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

會判斷如果資料庫錯誤導致註冊失敗,會回到註冊頁面

這是註冊寫進資料庫的部分

public bool AddUserData(UserData data)
{
    try
    {
        Connect();
        string id = Guid.NewGuid().ToString();
        string strSQL = @"INSERT INTO `userdata` (`id`, `account`, `password`, `city`, `village`, `address`)
                          VALUES (@id, @account, @password, @city, @village, @address)";
        MySqlCommand cmd = new MySqlCommand(strSQL, conn);
        cmd.Parameters.Add("@id", MySqlDbType.VarChar).Value = id;
        cmd.Parameters.Add("@account", MySqlDbType.VarChar).Value = data.account;
        cmd.Parameters.Add("@password", MySqlDbType.VarChar).Value = data.password1;
        cmd.Parameters.Add("@city", MySqlDbType.VarChar).Value = data.city;
        cmd.Parameters.Add("@village", MySqlDbType.VarChar).Value = data.village;
        cmd.Parameters.Add("@address", MySqlDbType.VarChar).Value = data.address;
        cmd.ExecuteNonQuery();
        return true;
    }
    catch
    {
        return false;
    }
    finally
    {
        Disconnect();
    }
}

然後進入登入頁面,這是前端的部分

@{
    ViewBag.Title = "Login";
    Layout = null;
}

@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")

<form style="margin-left:10px;" method="post" action="">
    <h1>請輸入帳號及密碼</h1>
    <div>
        <span style="color:red">@ViewBag.Msg</span>
    </div>
    <div class="form-group">
        <label for="exampleInputEmail1">帳號</label>
        <input type="text" class="form-control" id="Account" name="account" placeholder="輸入帳號" value="">
        <small id="emailHelp" class="form-text text-muted">請輸入英數字</small>
    </div>
    <div class="form-group">
        <label for="exampleInputPassword1">密碼</label>
        <input type="password" class="form-control" id="Password1" name="password" placeholder="輸入密碼" value="">
    </div>
    <button type="submit" class="btn btn-primary">登入</button>
    <button type="button" class="btn btn-warning" onclick="register()">註冊</button>
</form>

<script>
    function register()
    {
        location.href = "/Home/Index";
    }
</script>

如果還沒有帳號就按下 註冊 進入註冊頁面

今天大概分享到這裡
明日待續~

--
小弟不才,
如果有謬誤或是要補充的,
都歡迎一起來討論!


上一篇
[Day 26] 用ASP.NET MVC 做簡單的註冊及登入系統(二)
下一篇
[Day 28] 用ASP.NET MVC 做簡單的註冊及登入系統(四)
系列文
ASP.NET MVC網頁程式介紹30

尚未有邦友留言

立即登入留言