在数据库中添加新条目时,我想从上一页获取要输入的ID值.我可以毫不费力地将ID从初始页面传递到控制器Create方法,该方法显示提交表单的视图.但我不确定提交表格后如何才能访问它.

我try 过使用TempData、viewData和ViewBag,但在try 使用第二种方法检索它时,我看不到它的值.

    [HttpGet]
    public IActionResult Create(int? id){

         // I see the value here
    
            Debug.WriteLine(id);
            TempData["carid"] = id;
            Debug.WriteLine(TempData["carid"]);  
    
            return View(); // displays new entry form 
        }
        
        // called after the new entry form is submitted 
        [HttpPost]  
        public async Task<IActionResult> Create(RecordsViewModel addRecord)
        {
    
          // NO value here
    
            var carId = TempData["carid"]; 
            Debug.WriteLine(carId);   
    
    
            var record = new Records()
            {
                ID = carId, // value here is null 
                Date = addRecord.Date,
                Name = addRecord.Name,
                Cost = addRecord.Cost,
            };
    
            await carRep.Records.AddAsync(record);
            await carRep.SaveChangesAsync();
            return RedirectToAction("Create");
    
        }

如有指导,不胜感激,谢谢!

推荐答案

我try 过使用TempData、ViewData和ViewBag,但我看不到 当try 在第二个方法中检索它时,.

那么,您无法检索值的原因是它们都不是持久性数据容器.一旦操作被重定向,数据将不再位于临时数据、视图数据或视图包中,这只是一次.

为了保持数据从一个动作到另一个动作,即使在页面重定向后,你可以使用session,这是数据持久化或可以保持数据,只要你想要的.

您可以执行以下操作:

设置值:

[HttpGet]
 public IActionResult Create(int? id)
 {

     // I see the value here

     Debug.WriteLine(id);
     //TempData["carid"] = id;
     //Just for testing
     HttpContext.Session.SetInt32("carid", (int)id!);
 
     return View(); // displays new entry form 
 }

获取价值:

[HttpPost]
public async Task<IActionResult> Create(RecordsViewModel addRecord)
{

    // NO value here

    //Just for testing
    var carId = HttpContext.Session.GetInt32("carid");

   // var carId = TempData["carid"];
    Debug.WriteLine(carId);


    //var record = new Records()
    //{
    //    ID = carId, // value here is null 
    //    Date = addRecord.Date,
    //    Name = addRecord.Name,
    //    Cost = addRecord.Cost,
    //};

    //await carRep.Records.AddAsync(record);
    //await carRep.SaveChangesAsync();
    return RedirectToAction("Create");

}

Note:为了测试这个场景,我对您的代码中的一些代码进行了注释.只要你需要就可以使用它.

Program.cs:

builder.Services.AddSession(options =>
{
    options.Cookie.Name = "YourCookieName";
    options.IdleTimeout = TimeSpan.FromMinutes(2);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

中间件订单:

app.UseRouting();
app.UseSession();
app.UseAuthorization();

输出:

enter image description here

enter image description here

Note:有关更多实现示例,请参阅refer to this official document.

Csharp相关问答推荐

在实际上是List T的 IESEARCH上多次调用First()是否不好?

无法使用ternal- .net修复可空警告

如何使嵌套for-loop更高效?

Dapper是否可以自动扩展类成员

我无法在Ubuntu下编译使用microsoft.extension.configurationbuilder jsonapi和mono mcs的c#应用程序

处理. netstandard2.0项目中HttpClient.SslProtocol的PlatformNotSupportedException问题""

在. net毛伊岛窗口的深度链接已经创建""

如何使用C#Interop EXCEL创建度量衡

如何在ASP.NET Core8中启用REST应用程序的序列化?

如何捕获对ASP.NET核心应用程序的所有请求并将其发送到一个页面

显示文档的ECDsa签名PDF在Adobe Reader中签名后已被更改或损坏

在IAsyncEnumerable上先调用,然后跳过(1)可以吗?

C#按名称从类获取属性值类型<;t>;,我需要反射吗?

EF Core 7-忽略模型绑定中的虚拟属性

我应该为C#12中的主构造函数参数创建私有属性吗?

DropDownListFor未显示选定值

如何将 colored颜色 转换为KnownColor名称?

最小API定义的Swagger标头参数

Excel将';@';添加到具有范围的公式中

如何在JSON:API中定义的&过滤查询参数系列&标准的GET请求中传递多个相关参数?