尝试传递View模型时获取Null Value参考

时间:2015-07-30 16:10:21

标签: asp.net-mvc-5 asp.net-mvc-viewmodel

我在尝试将数据传递给视图模型时收到错误空引用异常

视图模型

 public class AccommodationApplicationViewModel
{
    public AccommodationApplicationViewModel() { }

    public PropertyRentingApplication _RentingApplicationModel { get; set; }

    public PropertyRentingPrice _PropertyRentingPriceModel { get; set; }

}

控制器方法

[Authorize]
    [HttpGet]
    public ActionResult ApplyForAccommodation()
    {

        int _studentEntityID = 0;

        //PropertyRentingApplication PropertyRentingApplicationModel = new PropertyRentingApplication();

        AccommodationApplicationViewModel PropertyRentingApplicationModel = new AccommodationApplicationViewModel();

        if (User.Identity.IsAuthenticated)
        {
            _studentEntityID = _studentProfileServices.GetStudentIDByIdentityUserID(User.Identity.GetUserId());

            if (_studentEntityID != 0)
            {
                bool StudentCompletedProfile = _studentProfileServices.GetStudentDetailedProfileStatusByID(_studentEntityID);

                if (StudentCompletedProfile)
                {

                    PropertyRentingApplicationModel._RentingApplicationModel.StudentID = _studentEntityID;

                    PropertyRentingApplicationModel._RentingApplicationModel.DateOfApplication = DateTime.Now;

                    var s = "dd";

                    ViewBag.PropertyTypes = new SelectList(_propertyManagementServices.GetAllPropertyType(), "PropertyTypeID", "Title");

                  //  ViewBag.PropertyRentingPrise = _propertyManagementServices.GetAllPropertyRentingPrice();

                    return PartialView("ApplyForAccommodation_partial", PropertyRentingApplicationModel);
                }
                else
                {
                    return Json(new { Response = "Please Complete Your Profile Complete Before Making Request For Accommodation", MessageStatus ="IncompletedProfile"}, JsonRequestBehavior.AllowGet);
                }

            }
            return Json(new { Response = "User Identification Fail!", MessageStatus = "IdentificationFail" }, JsonRequestBehavior.AllowGet);
        }

        return RedirectToAction("StudentVillageHousing", "Home");


    }
}

1 个答案:

答案 0 :(得分:1)

您尚未初始化_RentingApplicationModel_PropertyRentingPriceModel。最简单的解决方案是在AccommodationApplicationViewModel的构造函数中简单地初始化这些属性:

public AccommodationApplicationViewModel()
{
    _RentingApplicationModel = new PropertyRentingApplication();
    _PropertyRentingPriceModel = new PropertyRentingPrice();
}

然后,你应该没事。