Search code examples
asp.net-mvc-5asp.net-mvc-viewmodel

Getting Null Value reference when trying to pass View model


I getting error null reference exception while trying to pass data to view model

ViewModel

 public class AccommodationApplicationViewModel
{
    public AccommodationApplicationViewModel() { }

    public PropertyRentingApplication _RentingApplicationModel { get; set; }

    public PropertyRentingPrice _PropertyRentingPriceModel { get; set; }

}

Controller Method

[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");


    }
}

Solution

  • You haven't initialized either _RentingApplicationModel nor _PropertyRentingPriceModel. The easiest solution is to simply initialize these properties in your constructor for AccommodationApplicationViewModel:

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

    Then, you should be fine.