将模型从控制器传递到视图时(返回PartialView)(.NET Core)NullReferenceException

时间:2019-01-07 09:03:09

标签: .net model-view-controller core

我试图将UserProfileModel模型从控制器(UserProfileController)传递给View Index.cshtml。问题是,它以某种方式告诉我@ Model.UserObject.FirstName的NullReferenceException。我的数据库现在是空的(我想这可能是一个问题,但是我不确定是否传递了正确的逻辑)。

我尝试过的所有内容都放在下面的代码中

// View (Index)
@{
Layout = "_Layout";
}

@Html.Partial("_NavBar")
@Html.Partial("_SignInModal")
@Html.Partial("_SignUpModal")
@Html.Partial("_UserProfileContainer")
@Html.Partial("_Footer")
@Html.Partial("_EditProfile")


//PartialView (_AboutMe.cshtml)


@model Demo.Website.Models.UserProfileControllerViewModels.UserProfileViewModel
<div class="text-center mb-3">
<img class="img-about-me" alt="User icon" src="~/img/users icons/users icons1.png" />
</div>
<h2 class="h1-orange">Hi, I'm <span class="font-weight-bold">    </span>@Model.UserObject.FirstName</h2>

@' from here i think is irrelevant, if the first one passes, then all should after '@
<p class="mb-2"><span class="font-weight-bold">I come from:</span>
@Model.UserObject.Country</p>
<p class="mb-2"><span class="font-weight-bold">I live in:</span>
@Model.UserObject.City</p>

// Model

 public class UserProfileViewModel
{
    public User UserObject { get; set; } (User Class has the usual properties mentioned in the View)

}

// Controller 

public IActionResult Index()
    {



        return View();
    }

 [HttpGet]
    [Authorize]
    public IActionResult UserAboutMe(string userId, UserProfileViewModel model)
    {
        if (!ModelState.IsValid)
            throw new NotImplementedException("Error page - model state not valid");


        var user = DatabaseHandler<User>.Get(a => a.Id.Equals(userId));

        if (user == null)
            throw new NotImplementedException("Error page - could not find user");

        model.UserObject.Id=user.Id;

        if (model.UserObject.Id.Equals(user.Id))

            return PartialView("_AboutMe", model);

        else
        {
            throw new NullReferenceException("UserProfileViewModel points to null");

        }
    }

期望不会出错,并且要传递模型。

实际结果:

NullReferenceException:对象引用未设置为对象的实例。

_AboutMe.cshtml中的

AspNetCore.Views_UserProfile__AboutMe.ExecuteAsync()

<h2 class="h1-orange">Hi, I'm <span class="font-weight-bold"></span>@Model.UserObject.FirstName</h2>

_UserProfileContainer.cshtml中的AspNetCore.Views_UserProfile__UserProfileContainer.ExecuteAsync()

@Html.Partial("_AboutMe")

Index.cshtml中的AspNetCore.Views_UserProfile_Index.ExecuteAsync()

@Html.Partial("_UserProfileContainer")

0 个答案:

没有答案