C# DotNet Core Razor 页面,从 pageModel 为 createdModel 赋值

Posted

技术标签:

【中文标题】C# DotNet Core Razor 页面,从 pageModel 为 createdModel 赋值【英文标题】:C# DotNet Core Razor page, assign value to a createdModel from the pageModel 【发布时间】:2021-12-20 15:40:51 【问题描述】:

我正在做一个项目,我需要创建一个表单来填充数据库。

我可以使用 Asp-for 处理程序来填写表单并且它正在工作。

但我想在幕后添加一些信息,例如用户和创建日期。

我想做这样的事情:

public DateTime CurrentDate = DateTime.Now;
ModelForClients.CreationDate = CurrentDate; //That is what I would like to do. 
ModelForClients.UserType = currentUser // User which is filling the form I'm using login with Identity framework

您能告诉我如何从页面模型中添加信息吗?

模型页面 (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 ArchiProjectManager.Data;
using ArchiProjectManager.Models;
using Microsoft.AspNetCore.Identity;

namespace ArchiProjectManager.Pages.Users.Clients

    public class CreateModel : PageModel
    
        private readonly ArchiProjectManager.Data.ApplicationDbContext _context;

        public CreateModel(ArchiProjectManager.Data.ApplicationDbContext context)
        
            _context = context;
            
        

        public IActionResult OnGet()
        
            return Page();
        

        [BindProperty]
        public ModelForClients ModelForClients 
            get; set;
        

        //Variables added for the form

        public DateTime CurrentDate = DateTime.Now;
        ModelForClients.CreationDate = CurrentDate; //That is what I would like to do. 
        ModelForClients.UserType = currentUser // User which is filling the form I'm using login with Identity framework





        //Need to continue to add the user name and current date for the creation




        // To protect from overposting attacks, see https://aka.ms/RazorPagesCRUD
        public async Task<IActionResult> OnPostAsync()
        
            if (!ModelState.IsValid)
            
                return Page();
            

            _context.ModelForClients.Add(ModelForClients);
            await _context.SaveChangesAsync();

            return RedirectToPage("./Clients");
        
    

前视图(剃须刀页面)

@page
@model CreateModel

@
    ViewData["Title"] = "Create";


<div class="adminContainer">


    <div>
        <a asp-page="/Users/Clients/Clients" class="btn btn-danger">
            <i class="bi bi-backspace-fill"></i>
        </a>
    </div>
    <h1>Create</h1>

    <h4>ModelForClients</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="ModelForClients.LastName" class="control-label"></label>
                    <input asp-for="ModelForClients.LastName" class="form-control" />
                    <span asp-validation-for="ModelForClients.LastName" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="ModelForClients.FirstName" class="control-label"></label>
                    <input asp-for="ModelForClients.FirstName" class="form-control" />
                    <span asp-validation-for="ModelForClients.FirstName" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="ModelForClients.Adress" class="control-label"></label>
                    <input asp-for="ModelForClients.Adress" class="form-control" />
                    <span asp-validation-for="ModelForClients.Adress" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="ModelForClients.Company" class="control-label"></label>
                    <input asp-for="ModelForClients.Company" class="form-control" />
                    <span asp-validation-for="ModelForClients.Company" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="ModelForClients.LegalRepresentative" class="control-label"></label>
                    <input asp-for="ModelForClients.LegalRepresentative" class="form-control" />
                    <span asp-validation-for="ModelForClients.LegalRepresentative" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="ModelForClients.VatNumber" class="control-label"></label>
                    <input asp-for="ModelForClients.VatNumber" class="form-control" />
                    <span asp-validation-for="ModelForClients.VatNumber" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <p>Utilisateur assigné: @User.Identity.Name</p>
                    <p>Date de création: @Model.CurrentDate </p>
                </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>

</div>

型号:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace ArchiProjectManager.Models

    public class ModelForClients
    
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ClientId  get; set; 
        public string LastName  get; set; 
        public string FirstName  get; set; 
        public string Adress  get; set; 
        public string Company  get; set; 
        public string LegalRepresentative  get; set; 
        public string VatNumber  get; set; 
        public virtual User User  get; set; 
        public DateTime CreationDate  get; set; 
        public DateTime ModificationDate  get; set; 
        public string UserType  get; set; 
        

    

【问题讨论】:

你好@Rena,它正在工作,非常感谢你 :D 我喜欢你制作小视频的方式。再次感谢您。 【参考方案1】:

您可以将所需的信息添加为hidden 输入。

<input name="CreationDate" value="@model.CreationDate" type="hidden" />
<input name="UserType" value="@model.UserType" type="hidden" />

【讨论】:

谢谢你和@Rena,它正在工作:D 不客气 :)【参考方案2】:

首先,您需要知道对于复杂类型的每个属性,模型绑定会在源中查找名称模式 prefix.property_name

其次,只有inputselect元素可以表单提交。 p 不能通过表单提交传递给后端。

如下更改您的页面:

<div class="form-group">
    <p>Utilisateur assigné: @User.Identity.Name</p>
    //add this...
    <input asp-for="ModelForClients.UserType" value="@User.Identity.Name" type="hidden" />
    <input asp-for="ModelForClients.CreationDate" value="@Model.CurrentDate" type="hidden" />

    <p>Date de création: @Model.CurrentDate </p>        
</div>

后端:

public class CreateModel : PageModel

    public IActionResult OnGet()
    
        return Page();
    

    [BindProperty]
    public ModelForClients ModelForClients
    
        get; set;
    

    public DateTime CurrentDate = DateTime.Now;  
    public async Task<IActionResult> OnPostAsync()
                
        //...
        //no need to set the value like below:
        //ModelForClients.CreationDate = CurrentDate; 
        //ModelForClients.UserType = currentUser
    

结果:

此外,@Merna Mustafa 所做的也可以,但您需要在后端设置 CreationDateUserType property(not field)

[BindProperties]   //use BindProperties to bind all the properties, 
                   //then you no need add multiple BindProperty attributes
public class CreateModel: PageModel

    public IActionResult OnGet()
    
        return Page();
    

    public ModelForClients ModelForClients
    
        get; set;
    
    //add properties here......
    public DateTime CurrentDate  get; set;  = DateTime.Now;
    public string UserType  get; set; 
    public async Task<IActionResult> OnPostAsync()
    
        ModelForClients.CreationDate = CurrentDate; 
        ModelForClients.UserType = UserType;
        //...
        return RedirectToPage("./Clients");
    

页面:

<input name="CreationDate" value="@Model.CurrentDate" type="hidden" />
<input name="UserType" value="@User.Identity.Name" type="hidden" />

不管怎样,这两个解决方案都告诉你模型绑定系统通过name="PropertyName"绑定属性

【讨论】:

以上是关于C# DotNet Core Razor 页面,从 pageModel 为 createdModel 赋值的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 ASP.NET Core 同时制作 Razor Page 和 C# 代码框架?

从 ASP.NET Core Razor 页面获取 DisplayAttribute.Prompt

Asp.net Core 3.1-如何从控制器返回到 Razor 页面?

将数据从 javascript 传递到 asp.net core 2 razor 页面方法

尝试从 ASP.NET Core MVC Razor 中的 _Layout 页面重定向时出错

在Asp Core razor页面中使用LINQ从两个表中选择数据