由于这是一个异步方法,因此返回表达式的类型必须是“Data”类型,而不是 ASP.NET 和 Entity Framework 中的“Task<Data>”错误

问题描述 投票:0回答:1
[HttpGet]
public async Task<IActionResult> View(Guid id)
{
    var employee = await mvcDemoDbContext.Employees.FirstOrDefaultAsync(x => x.Id == id);

    if(employee != null)
    {
        var viewModel = new UpdateEmployeeViewModel()
        {
            Id = employee.Id,
            Name = employee.Name,
            Email = employee.Email,
            Salary = employee.Salary,
            Department = employee.Department,
            DateOfBirth = employee.DateOfBirth
        };

        return View(viewModel);
    }

    return RedirectToAction("Index");
}

在此函数中,我收到标题中提到的错误。

如何解决这个问题?

当我使用时

return await View(viewModel);

而不是

return View(viewModel);

然后视图不会显示。它正在重定向到

Index
。但是当我尝试使用
return View();
时,它显示了视图,但没有达到预期的结果。

这是

view.cshtml
文件的标记:

@model ASPNETMVCCRUD.Models.UpdateEmployeeViewModel

@{
}
<h1> Update Employee Information</h1>
<form method="post" action="View" class="mt-5">
    <div class="mb-3">
        <label for="" class="form-label">Id</label>
        <input type="text" class="form-control" asp-for="Id" readonly>
    </div>
    <div class="mb-3">
        <label for="" class="form-label">Name</label>
        <input type="text" class="form-control" asp-for="Name">
    </div>
    <div class="mb-3">
        <label for="" class="form-label">Email</label>
        <input type="email" class="form-control" asp-for="Email">
    </div>
    <div class="mb-3">
        <label for="" class="form-label">Salary</label>
        <input type="number" class="form-control" asp-for="Salary">
    </div>
    <div class="mb-3">
        <label for="" class="form-label">Date of Birth</label>
        <input type="date" class="form-control" asp-for="DateOfBirth">
    </div>
    <div class="mb-3">
        <label for="" class="form-label">Department</label>
        <input type="text" class="form-control" asp-for="Department">
    </div>

    <button type="submit" class="btn btn-primary">Submit</button>
</form>
asp.net-mvc async-await entity-framework-core
1个回答
0
投票

我会避免将您的方法命名为“View”,而是使用“Detail”之类的名称,因此“/Employee/Detail/xxxxx-xxx-xxxx-xxxxxx”应该调用的

View()
方法是控制器的基础
View(object)
告诉渲染引擎使用提供的视图模型编写 HTML。此方法不是
async
,但 ASP.Net 似乎正在根据名称解析您的控制器操作,并期待
await
,因为您的方法名为“View”。

要保留“查看”路线名称也可能适用于:

return base.View(viewModel); 

...或者您可以将该方法命名为“Detail”,但显式设置路由以映射到“/View”。

[HttpGet]
[Route("View/{id}")]
public async Task<IActionResult> ViewDetail(Guid id)    
© www.soinside.com 2019 - 2024. All rights reserved.