【发布时间】:2021-05-14 17:09:40
【问题描述】:
为什么我收到输入表单错误?
@foreach (var user in Model.UsersWithItemsOption2)
{
<div>
<div>@user.Items</div>
@string.Join(", ", user.Items.Select(a => a.ItemName).ToList());
<div>@user.Items.Select(a => a.ItemName)</div>
<form method="post">
//error
<input asp-for="@user.Items.Select(a => a.ItemName)" />
//error
<button type="submit">Save</button>
</form>
</div>
}
这是它的 C# 文件。
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using ArrayCheckNetCore.Areas.Identity.Data;
using ArrayCheckNetCore.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System.Linq;
namespace ArrayCheckNetCore.Areas.Identity.Pages.Account.Manage
{
public class PersonalDataModel : PageModel
{
/// Inject DbContext
readonly CheckArrayContext Context;
/// Inject UserManager
readonly UserManager<ApplicationUser> UserManager;
public IEnumerable<ApplicationUser> UsersWithItemsOption2 { get; set; } = new
List<ApplicationUser>();
public IEnumerable<ApplicationUser> UsersWithItemsOption1 { get; set; } = new
List<ApplicationUser>();
public string Name { get; set; }
public PersonalDataModel(
CheckArrayContext Context,
UserManager<ApplicationUser> UserManager)
{
this.Context = Context;
this.UserManager = UserManager;
}
public async Task<IActionResult> OnGetAsync()
{
UsersWithItemsOption2 = await UserManager
.Users
.Include(a => a.Items)
.ToListAsync();
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
await Context.SaveChangesAsync();
return RedirectToPage("");
}
}
}
我得到一个错误
InvalidOperationException:模板只能用于字段访问、属性访问、一维数组索引或单参数自定义索引器表达式
我认为问题在于,它无法在表单提交上设置属性,或者asp-for='@user.Items.Select(a => a.ItemName)' 可能未在文件的上下文中定义。
如果有人知道如何解决此错误,谢谢。
【问题讨论】:
-
您想为
user.Items中的每个项目创建一个输入? -
您好,我的回答有用吗?
标签: c# asp.net-mvc asp.net-core asp.net-core-mvc