Razor pages - RouteData null on Post

826 views Asked by At

I am trying to learn MVC and Razor pages (I am new to web development) and I am having an NullReferenceException on Post because RouteData is null. I don't have this issue on the Get. The page loads normally, but as soon as I click the Filter button, the exceptions shows. I can't even debug the OnPostAsync because it doesn't even enter the method. This is my page:

<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>

And this is the code:

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

There are 1 answers

0
Matias On BEST ANSWER

Found the issue. I was using [BindProperty] on a model not being used on the page:

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

I just removed the [BindProperty] and it was resolved.