iT邦幫忙

0

MVC 自學註冊系統卻抓到null值

mvc

我是跟這位老師學的:Step By Step
https://www.youtube.com/watch?v=OYGpsJhrbBc

可是我做的註冊系統卻抓不到正確的值,不知道是不是我哪裡寫錯了。
也重覆影片好幾次,都沒發現到是不是字或哪裡打錯。如下圖
環境:vs2017,MSSQL 2014

///////////// 這是我的controller //////////

using System.Web.Mvc;
using MenberSystem.Models;
using System.Linq;
using System;
using System.Data.SqlClient;
using System.Data;
using System.Web.Security;
using System.Activities.Statements;
using System.Transactions;

namespace MenberSystem.Controllers
{
 
    public class RegisterController : Controller
    {
        
        // Get Registe
        [AllowAnonymous]
        public ActionResult Index()
        {
            return View();
        }

       
        //Post Registe
        [HttpPost] //只允許透過post動詞通過
        public ActionResult Index([Bind(Exclude = ("ID,Password,Name,Email,City,Gender,Age"))] Menber menber)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    using (MenberSystemEntities2 db = new MenberSystemEntities2())
                    {
                        if (db.Menber.Where(p => p.ID == menber.ID).FirstOrDefault() != null)
                        {
                            ModelState.AddModelError("model.ID", "換別的帳號");
                            return View(menber);
                        }
                        using (TransactionScope transactionScope = new TransactionScope())
                        { 
                            menber.Password = menber.Password;
                        db.Menber.Add(menber);
                        db.SaveChanges();
                        }
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("ID", ex.Message);
                    return View(menber);
                }
                return RedirectToAction("Index", "Home");
            }
            else
            {
            return View(menber);
            }
        }        
    }  
}

///////////// 這是我的View /////////////

@model MenberSystem.Models.Menber

@{
    ViewBag.Title = "Registe";
}

<h2 style="text-align:center;">註冊</h2>
<!DOCTYPE html>
<html>
<head>
    <tltle style="text-align:center;">填寫基本資料</tltle>
</head>

<body>
    @using (Html.BeginForm("Index", "Register", FormMethod.Post))

    {
        @(Html.ValidationSummary(true))
        @Html.AntiForgeryToken()


        <div class="form-horizontal">
            <h4>Registe Page</h4>
            <hr />
            <!--帳號-->
            <div class="editor-field">
                <form action="" method="post">
                    <!--前面的文字-->
                    @Html.LabelFor(model => model.ID, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        <!--顯示 EditorBox 與 屬性規格-->
                        @Html.EditorFor(model => model.ID, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.ID, "", new { @class = "text-danger" })
                    </div>
                </form>
            </div>

            <!--密碼-->
            <div class="editor-field">
                <form action="" method="post">
                    @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
                    </div>
                </form>
            </div>
            <!--姓名-->
            <div class="editor-field">
                @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
                </div>
            </div>

            <!--信箱-->
            <div class="editor-field">
                @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
                </div>
            </div>

            <!--性別-->
            <div class="editor-field">
                @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Gender, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })
                    <!--@Html.RadioButtonFor(m => m.Gender, "女性") 女姓-->
                    <!--@Html.RadioButtonFor(m => m.Gender, "男性", new { @checked = "checked" }) 男性-->
                </div>
            </div>

            <!--居住地-->
            <div class="editor-field">
                @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })

                    <!-- @Html.DropDownList("City", new SelectList(new[] { "北部", "中部", "南部", "東部" }))
                    @{
                        List<SelectListItem> cityList = new List<SelectListItem>
                                                                    {
                                                                        new SelectListItem { Text = "北部",Value = "1"},
                                                                    new SelectListItem { Text = "中部", Value = "2" },
                                                                    new SelectListItem { Text = "南部", Value = "3" },
                                                                    new SelectListItem { Text = "東部", Value = "4" }
                                                                    };
                    }-->
                    @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
                </div>
            </div>

            <!--生日-->
            <div class="editor-field">
                @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class=" container">
                <button type="submit" class="btn btn-success">註冊</button>
                <button type="reset" class=" btn btn-warning">清除</button>
            </div>


            <script src="~/Scripts/bootstrap.js"></script>
            <script src="~/Scripts/jquery-3.3.1.js"></script>
            <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
            <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>


        </div>
    }
</body>
</html>


題外話:影片中的TransactionScope我卻用不出來,他都會顯示錯誤,我也有using過System.Transaction,可是一樣是錯誤的。請問隱含轉換成IDisposable是甚麼意思?
https://ithelp.ithome.com.tw/upload/images/20190502/20116639t00jUTXVwu.png

看更多先前的討論...收起先前的討論...
題外話 你要先了解using 是什麼
Homura iT邦高手 1 級 ‧ 2019-05-02 15:26:16 檢舉
Code可以貼上來嗎?
不要用截圖.....
抱歉,我現在google一下using的用法
對不起,我修改了
Homura iT邦高手 1 級 ‧ 2019-05-02 15:45:12 檢舉
拜託用編輯貼在上面...
用程式碼區塊包起來@@

2 個回答

1
Homura
iT邦高手 1 級 ‧ 2019-05-02 16:06:25
最佳解答

先來講一下你的TransactionScope為什麼會跳錯誤.....
因為System.Activities.StatementsSystem.Transactions2個命名空間
都有TransactionScope這個方法....
你先把using System.Activities.Statements這段註解掉應該就不會跳那個錯誤
或是使用全名

using (System.Transactions.TransactionScope sc =new System.Transactions.TransactionScope())
{

}

然後你為什麼抓不到欄位
原因是這段...

public ActionResult Index([Bind(Exclude = ("ID,Password,Name,Email,City,Gender,Age"))] Menber menber)

Bind的Exclude是不包含的欄位...
你應該要改成Include....

看更多先前的回應...收起先前的回應...
[HttpPost] //只允許透過post動詞通過
        public ActionResult Index([Bind(Include =("ID,Password,Name,Email,Age,Gender"))] Menber menber)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    using (MenberSystemEntities2 db = new MenberSystemEntities2())
                    {
                        if (db.Menber.Where(p => p.ID == menber.ID).FirstOrDefault() != null)
                        {
                            ModelState.AddModelError("model.ID", "換別的帳號");
                            return View(menber);
                        }
                        db.Menber.Add(menber);
                        db.SaveChanges();
                           
                       
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("ID", ex.Message);
                    return View(menber);
                }
                return RedirectToAction("Index", "Home");
            }
            else
            {
            return View(menber);
            }
        }        

Homura大大,除了Password抓不到值,其他都抓到值了!

VIEW跟MODEL那邊我都檢查過了,Password這邊沒有打錯字...

  public int Num { get; set; }
        [Required(ErrorMessage = "請輸入帳號")]
        public string ID { get; set; }
        [Required(ErrorMessage = "請輸入密碼")]
        public string Password { get; set; }
        public string Name { get; set; }
        [Required(ErrorMessage = "請輸入信箱")]
        public string Email { get; set; }
        public Nullable<int> Gender { get; set; }
        public string City { get; set; }
        public string Age { get; set; }
        public string LoginMessLoginErrorMsg { get; set; }
Homura iT邦高手 1 級 ‧ 2019-05-02 16:45:38 檢舉

terpoo1250
我在想Password是不是系統內建的保留字詞
你把欄位改成pwd看看抓不抓的到

Homura iT邦高手 1 級 ‧ 2019-05-02 16:51:54 檢舉

terpoo1250
還有密碼不應該用明碼表示....
你要改成密碼型態才對
model

[Required]
[DataType(DataType.Password)]
public string password { get; set; }

view

@Html.PasswordFor(m => m.password)

@Homura 大
剛剛測試過了,改成pwd或者Pwd都無法抓到值...

Homura iT邦高手 1 級 ‧ 2019-05-02 17:28:36 檢舉

terpoo1250
仔細一看你的前端怎麼一堆<form>元素
把那些都刪掉....
外面已經有@using (Html.BeginForm)不需要其他form元素....

Homura
謝謝,已經可以寫進資料庫了...
真的很謝謝你,我學了好多

0
小魚
iT邦大師 1 級 ‧ 2019-05-02 16:11:36

C#基礎的東西學會了嗎?
如果之前沒學過,
還是先從基礎開始學,
你這畢竟是有點進階的東西了.

然後我猜他應該是用Entity之類的連資料庫,
所以你現在已經可以連到資料庫了嗎?

你好,我是用Entity的資料庫,他跟ssms的資料庫有同步。
我已經做好Log In的系統了,我在ssms中的新增的會員資料,可以在我寫的網頁做登入,這樣應該算安裝好資料庫了對嗎?

小魚 iT邦大師 1 級 ‧ 2019-05-02 16:16:36 檢舉

那連線應該是可以了,
Homura大大說的問題先處理,
再看看能不能正常運行吧.

我要發表回答

立即登入回答