Thứ Ba, 11 tháng 10, 2022

[.NET] Truyền tham số trong .NET

 Có 2 cách truyền tham số thông dụng:

- Truyền thông qua Action Link

- Truyền thông qua thẻ Form.


1. Truyền thông qua Action Link.

Trong Controller

        [HttpGet]

        public ActionResult Index()

        {

         

            return View();

        }


        [HttpGet]

        public ActionResult Hello(String HoTen)

        {

            ViewBag.ht = HoTen;

            return View();

        }

Trong View Index.cshtml

    <div>

        @Html.ActionLink("Click here", "Hello", "Hello", new { @HoTen = "TranKhanh" }, new { @id = "id", @class = "new-class" })

    </div>

Trong View Hello.cshtml

    <div> 

        @{ 

            if(ViewBag.ht != null)

            {

                <span>@ViewBag.ht</span>

            }

        }

    </div>

Trong đó:

- new { @HoTen = "TranKhanh" }  là tham số truyền vào, ở đây là HoTen

2. Truyền tham số qua thẻ Form

Trong Controller

     [HttpGet]

        public ActionResult DangNhap()

        {

            return View();

        }

        [HttpPost]

        public ActionResult DangNhap(FormCollection f)

        {

            if (f["txtUsername"] == "Khanh" && f["txtPassword"]=="123456")

            {

                ViewBag.Message = "Dang nhap thanh cong";

            }

            else

                ViewBag.Message = "Dang Nhap that bai";

            return View();

        }


Trong Views

        @*Tao the Form*@

        @using (Html.BeginForm("DangNhap", "ThongTinTaiKhoan", FormMethod.Post))

        {

         <span>Họ tên:</span>@Html.TextBox("txtUsername", "", new {@class = "new-class" }) <br /> <br />

         <span>Mật khẩu:</span> @Html.TextBox("txtPassword", "", new {  @class = "new-class" }) <br />

         <input type="submit" />


        }

        @if(ViewBag.Message !=null)

        {

            <span>@ViewBag.Message</span>

        }

Ngoài ra cũng có thể truyền tham số trong thẻ Form.











Không có nhận xét nào:

Đăng nhận xét