Razor页面 - Post上的RouteData null

时间:2018-01-08 22:55:55

标签: c# post razor model routedata

我正在尝试学习MVC和Razor页面(我是Web开发新手)并且我在Post上有一个NullReferenceException,因为RouteData为null。我在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();
    }
}

1 个答案:

答案 0 :(得分:0)

发现了这个问题。我在页面上没有使用的模型上使用[BindProperty]

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

我刚删除了[BindProperty]并且已经解决了。