Cookies in Asp.Net Core
Packages
- "Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.5"
- "Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.25"
- "Microsoft.EntityFrameworkCore.Tools" Version="3.1.25"
- "Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.5"
Controllers[Folder]
TestController.cs
using Cookies.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
namespace Cookies.Controllers
{
public class TestController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
//Create variable of employee emp
public IActionResult Create(Employee emp)
{
//Set Create cookies
CookieOptions cookies = new CookieOptions();
//Set Expiry date of cookies
cookies.Expires = DateTime.Now.AddDays(1);
//Email is field name of Employee models
Response.Cookies.Append("Email", emp.Email, cookies);
ViewBag.Saved = "Cookie Saved";
return View();
}
public IActionResult ReadCookies()
{
//Get Cookies
ViewBag.Email = Request.Cookies["Email"].ToString();
return View("Create");
}
}
}
Models[Folder]
Employee.cs
namespace Cookies.Models
{
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Email { get; set; }
}
}
Views[Folder]
Test
Create.cshtml
@{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h1>@ViewBag.Saved</h1>
<a asp-action="ReadCookies" asp-controller="Test">Read Cookies</a>
<span>@ViewBag.Email</span>
Index.cshtml
@model Cookies.Models.Employee
@{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<h4>Employee</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Id" class="control-label"></label>
<input asp-for="Id" class="form-control" />
<span asp-validation-for="Id" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="City" class="control-label"></label>
<input asp-for="City" class="form-control" />
<span asp-validation-for="City" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Email" class="control-label"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a href="/Test/index">Back to List</a>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
0 Comments