Search code examples
asp.net-corerazor-pagesobject-reference

In my creation process I want to write to another entity than only the used


If I submit the page the first save goes without a problem

Than I assigned all values to the other entity which I want to write to create there a new record.

Why do I get an System Null Reference. I have in all fields the values which I want?

[Error Message

=== here is my c# Code ===========

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using WorkCollaboration.Data;
using WorkCollaboration.Models;

namespace WorkCollaboration.Pages.TimeReports
{
    public class CreateModel : PageModel
    {
        private readonly WorkCollaboration.Data.WorkCollaborationContext _context;

        public CreateModel(WorkCollaboration.Data.WorkCollaborationContext context)
        {
            _context = context;
        }

        public IActionResult OnGet()
        {
            CusContactDropDownDisp = _context.CusContactDropDown.ToList();  // Added for DropDown
            SupContactDropDownDisp = _context.SupContactDropDown.ToList();  // Added for DropDown
            return Page();
        }

        [BindProperty]
        public TimeReport TimeReport { get; set; }
        public IEnumerable<Models.CusContactDropDown> CusContactDropDownDisp { get; set; }
        public IEnumerable<Models.SupContactDropDown> SupContactDropDownDisp { get; set; }
        public Models.PointsforSupContact PointsforSupContact { get; set; }

        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://aka.ms/RazorPagesCRUD.
        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            TimeReport.TimeReportSupContactPointValue = (TimeReport.TimeReportHours * 10);

            _context.TimeReport.Add(TimeReport);
            await _context.SaveChangesAsync();

            //============================================
            // Adding new Point Record to Supplier Contact
            //============================================
            PointsforSupContact.PointsId = TimeReport.TimeReportId;
            PointsforSupContact.PointsSupContactId = TimeReport.TimeReportSupplierTalentContactId;
            PointsforSupContact.PointsInternalUserId = 1;     // User 1 Christof Oberholzer must be entered in Contacts and User
            PointsforSupContact.PointsDate = TimeReport.TimeReportDate;
            PointsforSupContact.PointsTotal = TimeReport.TimeReportSupContactPointValue;
            PointsforSupContact.PointsText = TimeReport.TimeReportText;
            PointsforSupContact.PointsTitle = "TimeReporting Points";

            _context.PointsforSupContact.Add(PointsforSupContact);
            await _context.SaveChangesAsync();



            return RedirectToPage("/TimeReportOverview/Index");
        }
    }
}

==== My Page ======

@page
@using Microsoft.AspNetCore.Localization
@using Microsoft.AspNetCore.Mvc.Localization
@model WorkCollaboration.Pages.TimeReports.CreateModel

@{
    ViewData["Title"] = "Create";
    ViewData["RandomId"] = Guid.NewGuid().GetHashCode();
}

@inject IViewLocalizer Localizer

<h1>Create</h1>
<h4>TimeReport</h4>
<p>
    <a asp-page="/TimeReportOverview/Index">Back to Index</a>
</p>
<hr />
<div class="row">
    <div class="col-md-4">
        <form method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="TimeReport.TimeReportSupContactPointValue" value="0"/>
            <div class="form-group">
                <label asp-for="TimeReport.TimeReportId" class="control-label"></label>
                <input asp-for="TimeReport.TimeReportId" value='@ViewData["RandomId"]' readonly="readonly" class="form-control" />
                <span asp-validation-for="TimeReport.TimeReportId" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="TimeReport.TimeReportCustomerNeedContactId" class="control-label"></label>
            </div>
            <select id="CusContactId" asp-for="CusContactDropDownDisp" asp-items="@(new SelectList(Model.CusContactDropDownDisp,"CusContactId","CusFullName"))">
                <option value="" selected disabled>--Choose Customer--</option>
            </select>
            <div class="form-group">
                <input asp-for="TimeReport.TimeReportCustomerNeedContactId" readonly="readonly" class="form-control" />
                <span asp-validation-for="TimeReport.TimeReportCustomerNeedContactId" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="TimeReport.TimeReportSupplierTalentContactId" class="control-label"></label>
            </div>
            <select id="SupContactId" asp-for="SupContactDropDownDisp" asp-items="@(new SelectList(Model.SupContactDropDownDisp,"SupContactId","SupFullName"))">
                <option value="" selected disabled>--Choose Supplier--</option>
            </select>
            <div class="form-group">
                <input asp-for="TimeReport.TimeReportSupplierTalentContactId" readonly="readonly" class="form-control" />
                <span asp-validation-for="TimeReport.TimeReportSupplierTalentContactId" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="TimeReport.TimeReportDate" class="control-label"></label>
                <input type="datetime-local" asp-for="TimeReport.TimeReportDate" class="form-control" />
                <span asp-validation-for="TimeReport.TimeReportDate" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="TimeReport.TimeReportHours" class="control-label"></label>
                <input asp-for="TimeReport.TimeReportHours" class="form-control" />
                <span asp-validation-for="TimeReport.TimeReportHours" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="TimeReport.TimeReportText" class="control-label"></label>
                <input asp-for="TimeReport.TimeReportText" class="form-control" />
                <span asp-validation-for="TimeReport.TimeReportText" class="text-danger"></span>
            </div>
            <div class="form-group">
                @Html.LabelFor(model => model.TimeReport.TimeReportState, htmlAttributes: new { @class = "form-group" })
                <div class="form-group">
                    @Html.DropDownListFor(model => model.TimeReport.TimeReportState, new List<SelectListItem>
                    {
                        new SelectListItem {Text = "Gebucht", Value = "Reported", Selected = true },
                        new SelectListItem {Text = "Kontrolliert", Value = "Controlled" },
                        new SelectListItem {Text = "Verrechnet / Noch nicht bezahlt", Value = "Invoiced / Not yet payed" },
                        new SelectListItem {Text = "Verrechnet / Bezahlt", Value = "Invoiced / Payed" },
                    }, new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.TimeReport.TimeReportState, "", new { @class = "text-danger" })
                </div>
             </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
                <a href="/TimeReportOverview/Index" class="btn btn-primary">Back to List</a>
            </div>
        </form>
    </div>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
<script>
    $("#CusContactId").on("change", function () {
        $("#TimeReport_TimeReportCustomerNeedContactId").val($("#CusContactId").val());
    });
    $("#SupContactId").on("change", function () {
        $("#TimeReport_TimeReportSupplierTalentContactId").val($("#SupContactId").val());
    });
</script>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Thank you for your help


Solution

  • First In your view:

    ViewData["RandomId"] = Guid.NewGuid().GetHashCode();
    

    GetHashCodemethod make the Guid to int,please make sure it matches the type in your model.

    Then the right way to add new PointsforSupContact is to create a new PointsforSupContact,so you need to delete the code:

     public Models.PointsforSupContact PointsforSupContact { get; set; }
    

    and change you code to:

     //...
     await _context.SaveChangesAsync();
     //add this line
     var PointsforSupContact=new PointsforSupContact();
     PointsforSupContact.PointsId = TimeReport.TimeReportId;
     //...