Distinguish synchronization vs asynchronous
1.1 In Model folder, add new file Demo class (Demo.cs) and define new class/new function as below:
public class Demo
{
public static string A()
{
Thread.Sleep(2000);
return "Function A";
}
public static int B()
{
Thread.Sleep(5000);
return new Random().Next();
}
public static void C()
{
Thread.Sleep(3000);
return;
}
}
1.2 Create new controller DemoController (DemoCtroller.cs), add new action SyncDemo() to run sync all method.
public class DemoController : Controller
{
public IActionResult DemoSync()
{
var sw = new Stopwatch();
sw.Start();
Demo.A();
Demo.B();
Demo.C();
sw.Stop();
return Content($"Chạy hết {sw.ElapsedMilliseconds}ms");
}
}
1.3 Run the page with URL /Demo/DemoSync and observe the results
1.4 Add 3 async functions similar to the above 3 functions:
#region Method Async
public static async Task<string> AA()
{
await Task.Delay(2000);
return "Function A";
}
public static async Task<int> BB()
{
await Task.Delay(5000);
return new Random().Next();
}
public static async Task CC()
{
await Task.Delay(3000);
return;
}
#endregion
1.5 Back to DemoController, we add AsyncDemo() action to test call async function.
public async Task<IActionResult> AsyncDemo()
{
var sw = new Stopwatch();
sw.Start();
var a = Demo.AA();
var b = Demo.BB();
var c = Demo.CC();
await a; await b; await c;
//Task.WaitAll();
sw.Stop();
return Content($"Chạy hết {sw.ElapsedMilliseconds}ms");
}
1.6 Run and observe the result
At the end of the exercise, you will be able to::
Create a form to upload file
Receive the uploaded file and save it to the folder with the original file name
Step 1: Create FileUploadController controller
public class FileUploadController : Controller
{
[HttpGet]
public IActionResult Index()
{
return View();
}
}
Step 2: Create form upload file
In this View Index(), we will design 2 separate forms used to upload a single and multiple files. In particular, the form must always have the value of the method attribute to POST and enctype attribute is multipart/form-data.
<form asp-action="UploadFile" enctype="multipart/form-data">
<h2>Upload Single File</h2>
<input type="file" name="myfile" />
<button>Upload</button>
</form>
<form asp-action="UploadFiles" enctype="multipart/form-data">
<h2>Upload Multiple File</h2>
<input type="file" name="myfiles" multiple />
<button>Upload</button>
</form>
Run to see the result
Step 3: Adding UploadFile(), UploadFiles() actions into controller.
All uploaded files are saved to the data folder in wwwroot folder
[HttpPost]
public IActionResult UploadFile(IFormFile myfile)
{
if (myfile == null)
{
ViewBag.Message = "Chưa chọn file upload.";
}
else
{
var fullPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "data", myfile.FileName);
using (var f = new FileStream(fullPath, FileMode.CreateNew))
{
myfile.CopyTo(f);
}
}
return View("Index");
}
public IActionResult UploadFiles(List<IFormFile> myfiles)
{
if (myfiles == null || myfiles.Count == 0)
{
ViewBag.Message = "Chưa chọn file upload.";
}
else
{
foreach (var myfile in myfiles)
{
var fullPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "data", myfile.FileName);
using (var f = new FileStream(fullPath, FileMode.CreateNew))
{
myfile.CopyTo(f);
}
}
}
return View("Index");
}
Back to View Index (~/Views/FileUpload/Index.cshtml), add <div class="text-danger">@ViewBag.Message</div> in case error when upload file.
Step 5: Demo and observe the results.
After completing this lab, you have several abilities:
Transfer data between Controller and View
Read/write data from/to text/json file
Step 1: In Models folder, create new Student class
public class Student
{
[RegularExpression(@"\d{2}.01.104.\d{3}")]
public string Id { get; set; }
[MinLength(5, ErrorMessage ="Tối thiểu 5 kí tự")]
public string Name { get; set; }
public string? Image { get; set; }
[Range(0, 10, ErrorMessage = "Điểm từ 0 .. 10")]
public double Score { get; set; }
}
Step 2: Create new StudentController
public class StudentController : Controller
{
public IActionResult Create()
{
return View();
}
}
Step 3: Generate new view Index() with template Create, model Student.
Custom 2 or 4 buttons to Save to File:
<div class="form-group">
<input type="submit" name="btnSave" value="Save JSON" class="btn btn-primary" />
<input type="submit" name="btnSave" value="Save TEXT" class="btn btn-primary" />
</div>
Step 4: Add action Create() POST to handle upload file and store all information into JSON file.
[HttpPost]
public IActionResult Create(Student model, IFormFile Hinh)
{
if (Hinh != null)
{
var fullPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images", Hinh.FileName);
using (var f = new FileStream(fullPath, FileMode.CreateNew))
{
Hinh.CopyTo(f);
model.Image = Hinh.FileName;
}
}
if (btnSave == "Save JSON")
{
System.IO.File.WriteAllText("student.json", System.Text.Json.JsonSerializer.Serialize(model));
}
// The same for TEXT file
return View("Create", model);
}