Hi
I created project using asp.net core 2.2 razor page and i try to add login user id to some tables
my codes :
Model :
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace LibraryManage.Models
{
public class TestUserId
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[DataType(DataType.Date)]
public DateTime DateOfBearth { get; set; }
[ScaffoldColumn(false)]
public string UserId { get; set; }
[ForeignKey("UserId")]
public virtual ApplicationUser ApplicationUser { get; set; }
}
}
Create.cshtml :
@page
@model LibraryManage.Pages.TestUserIds.CreateModel
@{
ViewData["Title"] = "Create";
Layout = "~/Pages/Shared/_Layout.cshtml";
}
<h1>Create</h1>
<h4>TestUserId</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="TestUserId.Name" class="control-label"></label>
<input asp-for="TestUserId.Name" class="form-control" />
<span asp-validation-for="TestUserId.Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="TestUserId.DateOfBearth" class="control-label"></label>
<input asp-for="TestUserId.DateOfBearth" class="form-control" />
<span asp-validation-for="TestUserId.DateOfBearth" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-page="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Create.cshtml.cs :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using LibraryManage.Data;
using LibraryManage.Models;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
namespace LibraryManage.Pages.TestUserIds
{
[Authorize]
public class CreateModel : PageModel
{
private readonly ApplicationDbContext _context;
public CreateModel(ApplicationDbContext context)
{
_context = context;
}
public IActionResult OnGet(string userId)
{
var claimsIdentity = (ClaimsIdentity)User.Identity;
var claim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
userId = claim.Value;
TestUserId.UserId = userId;
return Page();
}
[BindProperty]
public TestUserId TestUserId { get; set; }
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
_context.TestUserId.Add(TestUserId);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
}
}
But not work
It always display userid as null value