Tạo Models
Product.cs (Class tạo trong folder Models)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Tạo_sản_phẩm_mới_khi_người_dùng_nhập_thông_tin_vào.Models
{
public class Product
{
private int _Id;
public int Id { get=>_Id;set { _Id = value; } }
private string _Name;
public string Name { get => _Name; set { _Name = value; } }
}
}
Tạo controller
Trong HomeController.cs trong folder Controllers, xóa những phương thức mặc định, sau đó tạo 2 phương thức cùng tên Create, mà phương thức Create thứ 2 có tham số truyền vào là 1 instance của lớp Product và trên đầu là [HttpPost]
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Tạo_sản_phẩm_mới_khi_người_dùng_nhập_thông_tin_vào.Models;
namespace Tạo_sản_phẩm_mới_khi_người_dùng_nhập_thông_tin_vào.Controllers
{
public class HomeController : Controller
{
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create([Bind(Include ="Id,Name")]Product pro)
{
return View(pro);
}
}
}
Tạo View
Bên HomeController.cs, Tạo 1 view có tên Create từ phương thức Create nào cũng được
Create.cshtml
@model Tạo_sản_phẩm_mới_khi_người_dùng_nhập_thông_tin_vào.Models.Product
@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@if (Model == null)
{
<h2>Create New Product</h2>
<form action="/Home/Create" method="post">
<div class="mb-3">
<label class="form-label">Mã sản phẩm</label>
<input type="text" class="form-control" name="Id" placeholder="Mã sản phẩm" />
</div>
<div class="mb-3">
<label class="form-label">Tên sản phẩm</label>
<input type="text" class="form-control" name="Name" placeholder="Tên sản phẩm" />
</div>
<button class="btn btn-outline-primary">Submit</button>
</form>
}
else
{
<h2>New Product</h2>
<ul>
<li>Product Id: @Model.Id</li>
<li>Product Name: @Model.Name</li>
</ul>
}
Tạo Layout
_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="/redirect?Id=9fLRaWQliBbz0ECLj4fqtEVVEaknSDhDxHclZjypxm4K7BtEopPujLJ6oDaqg5Cg" rel="stylesheet" type="text/css" />
<title>@ViewBag.Title</title>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-2 text-white" style="background-color:aquamarine; min-height:1050px; padding:0">
<ScrollViewer>
@Html.ActionLink("Create New Product", "Create", "Home")
</ScrollViewer>
</div>
<div class="col-md-10" style="min-height:610px">
@RenderBody()
</div>
</div>
</div>
</body>
</html>