I am attempting to pass the foreign key ParentId to the model Child which is being loaded as a modal dialogue from a Razor partial page (Pages > Shared > _Child.cshtml) via AJAX from the Parent Details Page (Pages > Parents > Details.chstml) . When I click on the button that triggers the modal, I get the following error in visual studio:
How can I load the parentId into data.Child.ParentId?
Create.cshtml.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using TelerikTest.Models.Scaffold;
namespace TelerikTest.Pages.Childs
{
public class CreateModel : PageModel
{
private readonly TelerikTest.Models.Scaffold.TelerikTestDBContext _context;
public CreateModel(TelerikTest.Models.Scaffold.TelerikTestDBContext context)
{
_context = context;
}
public IActionResult OnGet()
{
ViewData["AnotherTableId"] = new SelectList(_context.AnotherTables, "AnotherTableId", "AnotherTableName");
ViewData["ParentId"] = new SelectList(_context.Parents, "ParentId", "ParentName");
return Page();
}
[BindProperty]
public Child Child { get; set; }
public SelectList AnotherTableSelectList { get; set; } //add this...
// To protect from overposting attacks, see https://aka.ms/RazorPagesCRUD
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
_context.Children.Add(Child);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
public PartialViewResult OnGetChildPartial(int parentId)
{
AnotherTableSelectList = new SelectList(_context.AnotherTables, "AnotherTableId", "AnotherTableName");
var data = new CreateModel(_context);
//Debug.WriteLine("ParentId:"+parentId);
data.Child.ParentId = parentId;
data.AnotherTableSelectList = AnotherTableSelectList;
return Partial("/Pages/Shared/_Child.cshtml", data);
}
}
}