ViewModel becomes null after creating a POST request in ASP.NET MVC

306 Views Asked by At

I'm creating an edit user page which will modify a user's existing role name within the web app. However, upon POST request, the Edit's view model becomes null after containing the values from the form (checked this using breakpoints).

I then get a prompt message in Visual Studio saying:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

Microsoft.AspNetCore.Mvc.Razor.RazorPage\<TModel\>.Model.get returned null.

UserController.cs

        [HttpPost]
        public async Task<IActionResult> Edit(IFormCollection formCollection)
        {
            try
            {
                await _userControllerService.EditAzureUser(formCollection);
                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }

UserControllerService.cs

        public async Task EditAzureUser(IFormCollection formCollection)
        {
            string id = formCollection["User.PrincipalId"];
            string appRoleId = formCollection["User.AppRoleId"];
            //Edit logic here
        }

Edit.cshtml


@model CreateUserViewModel

@{
ViewData\["Title"\] = "Edit User";
}


    <label asp-for="User.PrincipalDisplayName" class="col-form-label">Name: </label>
    <input asp-for="User.PrincipalDisplayName" value="@Model.User.PrincipalDisplayName" readonly class="form-control"/>
    
    <label class="col-form-label">Role: </label>
    <select asp-for="User.AppRoleName" title="Select Role" required class="form-control"  style="margin-bottom: 1rem"/>
        @{
            foreach(var role in AppRole.Roles)
            {
                if(Model.User.AppRoleName == role)
                {
                    <option value="@role" selected>@role</option>
                } else
                {
                    <option value="@role">@role</option>
                }
            }
        }
    
    <input type="hidden" asp-for="User.AppRoleId"/>
    <input type="button" value="Cancel" class="btn btn-secondary btn-sm" onclick="goBack()" />
    <input type="submit" class="btn btn-info btn-sm" />

1

There are 1 best solutions below

1
Avrohom Yisroel On

Your POST method doesn't return a model to the view, but the view expects a non-null CreateUserViewModel, which it uses in the markup. My guess is that's why you're getting the NRE.

However, if the POST was successful, why are you going back to the edit page anyway? Either send them to another page (often a user list if this is an admin facility, or a "thank you page if it's for the users themselves), or modify the Razor in this view to show a message saying the edit was successful. Either way, you don't need the model.