0

我正在尝试学习 MVC 和 Razor 页面(我是 Web 开发的新手),并且由于 RouteData 为空,我在 Post 上遇到了 NullReferenceException。我在 Get 上没有这个问题。该页面正常加载,但只要我单击“过滤器”按钮,就会显示异常。我什至无法调试 OnPostAsync,因为它甚至没有进入方法。这是我的页面:

<div class="row">
    <div class="col-md-4">
        <form method="post">
            <div class="form-group">
                <label asp-for="Input.UserName" class="control-label"></label>
                <input asp-for="Input.UserName" class="form-control" />
            </div>
            <div class="form-group">
                <label asp-for="Input.Email" class="control-label"></label>
                <input asp-for="Input.Email" class="form-control" />
            </div>
            <div class="form-group">
                <input type="submit" value="Filter" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>

<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.UserList[0].UserName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.UserList[0].Email)
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model.UserList)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.UserName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Email)
                </td>
            </tr>
        }
    </tbody>
</table>

这是代码:

public class UsersModel : PageModel
{
    [BindProperty]
    public _userModel _UserModel { get; set; }

    [BindProperty]
    public InputModel Input { get; set; }

    internal IList<_userModel> userList = new List<_userModel>();
    public IList<_userModel> UserList { get => userList; set => userList = value; }

    public class InputModel
    {
        [Display(Name = "Username")]
        public string UserName { get; set; }

        [Display(Name = "Email")]
        public string Email { get; set; }
    }

    public async Task<IActionResult> OnGetAsync()
    {
        //Add all users to UserList
        return Page();
    }
    public async Task<IActionResult> OnPostAsync()
    {
        //Filter UserList
        return Page();
    }
}
4

1 回答 1

0

发现问题。我[BindProperty]在页面上未使用的模型上使用:

[BindProperty]
public _userModel _UserModel { get; set; }

我刚刚删除了[BindProperty]它并解决了。

于 2018-01-10T23:56:07.980 回答