iT邦幫忙

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

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

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

今天繼續昨天說的,
當驗證錯誤的時候,
要把之前輸入的資料保留下來,
通常除了密碼之外都會保留下來,

這是輸入畫面
https://ithelp.ithome.com.tw/upload/images/20180104/201056946qUodTYuNp.jpg

這是密碼輸入錯誤的畫面
https://ithelp.ithome.com.tw/upload/images/20180104/20105694X5mDUAmL1l.jpg

在ASP.NET MVC裡面有一種很簡單的方式,
就是利用ViewModel,
(其實就是Model)
首先要先建立一個Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCTest.Models
{
    public class UserData
    {
        public string account { get; set; }
        public string password1 { get; set; }
        public string password2 { get; set; }
        public string city { get; set; }
        public string village { get; set; }
        public string address { get; set; }
    }
}

注意Model的命名要跟前端的name一樣,大小寫也要一樣

然後在後端要做帶入Model的動作

public ActionResult Index()
{
    List<City> cityList = db.GetCityList();
    List<Village> villageList = new List<Village>();

    ViewBag.CityList = cityList;
    ViewBag.VillageList = villageList;
    return View(new UserData());
}

然後這是前端的部分,其中如果VillageList不是空的,會直接帶入VillageList的值

@{
    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>

前端首先帶入一個Model

@model MVCTest.Models.UserData

假如裡面有值,會將值帶到對應的欄位中

<input type="text" class="form-control" id="Account" name="account" placeholder="輸入帳號" value="@Model.account">

注意name跟Model的變數名稱是一樣的,方便直接傳到後端

然後這是後端接收的部分

[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
    {
        Response.Redirect("Login");
        return new EmptyResult();
    }
}

直接用Model接收值就可以了,不需要做任何動作

這是完整的後端程式碼

using MVCTest.Models;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCTest.Controllers
{
    public class HomeController : Controller
    {
        MyDataBase db = new MyDataBase();
        public ActionResult Index()
        {
            List<City> cityList = db.GetCityList();
            List<Village> villageList = new List<Village>();

            ViewBag.CityList = cityList;
            ViewBag.VillageList = villageList;
            return View(new UserData());
        }

        [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
            {
                Response.Redirect("Login");
                return new EmptyResult();
            }
        }

        [HttpPost]
        public ActionResult Village(string id = "")
        {
            List<Village> list = db.GetVillageList(id);
            string result = "";
            if (list == null)
            {
                //讀取資料庫錯誤
                return Json(result);
            }
            else
            {
                result = JsonConvert.SerializeObject(list);
                return Json(result);
            }
        }
    }
}

今天就先分享到這裡,
明天就要開始實作資料庫的操作了。

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


上一篇
[Day 25] 用ASP.NET MVC 做簡單的註冊及登入系統(一)
下一篇
[Day 27] 用ASP.NET MVC 做簡單的註冊及登入系統(三)
系列文
ASP.NET MVC網頁程式介紹30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 則留言

0
SunAllen
iT邦研究生 1 級 ‧ 2018-01-04 19:55:20

/images/emoticon/emoticon13.gif
專業啊!

小魚 iT邦大師 1 級 ‧ 2018-01-04 20:08:11 檢舉

感恩啊~
/images/emoticon/emoticon41.gif

我是覺得這算是基礎的,
以ASP.NET MVC來說。
還有很多要學習的東西...

0
ovo815428
iT邦新手 5 級 ‧ 2020-07-15 14:51:55

嗨~我去資軟業界實習,業師提供他們寫的公益專案也是做登入系統,講解Model–view–controller架構,可是我還是聽不懂。
我是管院商科的學生,平常學校課程教得很淺而且這個部分沒有教,我程式被當過,目前在實習,上網找到您的教學資源,這篇程式碼跟業師提供的公益專案相似度非常高,求神人指點,拜託!

小魚 iT邦大師 1 級 ‧ 2020-07-19 10:03:52 檢舉

真的要搞懂很不容易,
尤其是model,
不過至少先知道要怎麼寫就可以,

順著這個系列文章並且一步一步去操作,
應該能夠搞懂基本的流程,
剩下的很多需要靠經驗來學習,
當然如果有比較明確的問題可以來版上發問.

我要留言

立即登入留言