У меня две таблицы. Один называл «персонами», другой - «инцидентами»
В приложении у них обоих реализованы операции CRUD. Я хочу отобразить обе таблицы рядом друг с другом в одном представлении.
Есть два контроллера. Один для «людей», другой для «инцидентов».
Причина, по которой они оба имеют операции CRUD, заключается в том, что мне нужно, чтобы пользователь мог создавать записи о людях и записи об инцидентах отдельно, но чтобы оба отображались синхронно c друг с другом на одном экране. Я пытался использовать для этого ViewModel, но продолжаю сталкиваться с ошибками. Вот почему я сейчас прошу помощи.
Код модели:
public int PersonId { get; set; }
[Display(Name = "Service ID:")]
public string Service_ID { get; set; }
[Display(Name = "Rank/ Title:")]
public string Rank { get; set; }
[Display(Name = "Initials:")]
public string Initials { get; set; }
[Display(Name = "First Name:")]
public string First_Name { get; set; }
[Display(Name = "Middle Name:")]
public string Middle_Name { get; set; }
[Display(Name = "Surname:")]
public string Surname { get; set; }
[Display(Name = "Service:")]
public string Service { get; set; }
[Display(Name = "Corps:")]
public string Corps { get; set; }
[Display(Name = "Unit:")]
public string Unit { get; set; }
[Display(Name = "DOB::")]
[DataType(DataType.Date)]
public DateTime DOB { get; set; }
[Display(Name = "Gender:")]
public string Gender { get; set; }
[Display(Name = "Address:")]
public string Address { get; set; }
[Display(Name = "Phone:")]
public string Phone { get; set; }
[Display(Name = "Plate Number:")]
public string Vehicle_Registration { get; set; }
[Display(Name = "Make:")]
public string Make { get; set; }
[Display(Name = "Model:")]
public string Model { get; set; }
[Display(Name = "Year:")]
public string Year { get; set; }
[Display(Name = "Colour:")]
public string Colour { get; set; }
[Display(Name = "WOF Exp:")]
[DataType(DataType.Date)]
public DateTime WOF { get; set; }
[Display(Name = "REGO Exp:")]
[DataType(DataType.Date)]
public DateTime REGO { get; set; }
public int IncidentId { get; set; }
[Display(Name = "Event Number")]
public string Event { get; set; }
[Display(Name = "POC")]
public string MP { get; set; }
[Display(Name = "Incident/ Offence")]
public string Incident { get; set; }
[Display(Name = "Location of Incident")]
public string Location { get; set; }
[Display(Name = "Date/Time of Incident")]
public DateTime Date_Time { get; set; }
[Display(Name = "Role in Incident")]
public string Role { get; set; }
[Display(Name = "Text")]
public string IncidentDetail { get; set; }
[Display(Name = "BOR")]
public string BOR { get; set; }
[Display(Name = "Action Taken")]
public string Action { get; set; }
Persons Context
public class PersonsContext : DbContext
{
public PersonsContext (DbContextOptions<PersonsContext> options)
: base(options)
{
}
public DbSet<Persons> Persons { get; set; }
public DbSet<Incidents> Incidents { get; set; }
}
Персональный контроллер
public class PersonsController: Controller
{
private readonly PersonsContext _context;
public PersonsController(PersonsContext context)
{
_context = context;
}
// GET: Persons
public async Task<IActionResult> Index(string searchstring, string searchstring1, string searchstring2, string searchstring3)
{
var persons = from m in _context.Persons
select m;
if (!String.IsNullOrEmpty(searchstring))
{
persons = persons.Where(s => s.Service_ID.Contains(searchstring));
}
if (!String.IsNullOrEmpty(searchstring1))
{
persons = persons.Where(s => s.First_Name.Contains(searchstring1));
}
if (!String.IsNullOrEmpty(searchstring2))
{
persons = persons.Where(s => s.Surname.Contains(searchstring2));
}
if (!String.IsNullOrEmpty(searchstring3))
{
persons = persons.Where(s => s.Vehicle_Registration.Contains(searchstring3));
}
return View(await persons.ToListAsync());
}
// GET: Persons/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var persons = await _context.Persons
.FirstOrDefaultAsync(m => m.PersonId == id);
if (persons == null)
{
return NotFound();
}
return View(persons);
}
// GET: Persons/Create
public IActionResult Create()
{
return View();
}
// POST: Persons/Create
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Service_ID,Rank,Initials,First_Name,Middle_Name,Surname,Service,Corps,Unit,DOB,Gender,Address,Phone,Vehicle_Registration,Make,Model,Year,Colour,WOF,REGO")] Persons persons)
{
if (ModelState.IsValid)
{
_context.Add(persons);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(persons);
}
// GET: Persons/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var persons = await _context.Persons.FindAsync(id);
if (persons == null)
{
return NotFound();
}
return View(persons);
}
// POST: Persons/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Service_ID,Rank,Initials,First_Name,Middle_Name,Surname,Service,Corps,Unit,DOB,Gender,Address,Phone,Vehicle_Registration,Make,Model,Year,Colour,WOF,REGO")] Persons persons)
{
if (id != persons.PersonId)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(persons);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!PersonsExists(persons.PersonId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(persons);
}
// GET: Persons/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var persons = await _context.Persons
.FirstOrDefaultAsync(m => m.PersonId == id);
if (persons == null)
{
return NotFound();
}
return View(persons);
}
// POST: Persons/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var persons = await _context.Persons.FindAsync(id);
_context.Persons.Remove(persons);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool PersonsExists(int id)
{
return _context.Persons.Any(e => e.PersonId == id);
}
}
Контекст инцидентов
public class IncidentsContext : DbContext
{
public IncidentsContext (DbContextOptions<IncidentsContext> options)
: base(options)
{
}
public DbSet<MP_EST.Models.Incidents> Incidents { get; set; }
}
}
Контроллер инцидентов
public class IncidentsController : Controller
{
private readonly IncidentsContext _context;
public IncidentsController(IncidentsContext context)
{
_context = context;
}
// GET: Incidents
public async Task<IActionResult> Index()
{
return View(await _context.Incidents.ToListAsync());
}
// GET: Incidents/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var incidents = await _context.Incidents
.FirstOrDefaultAsync(m => m.IncidentId == id);
if (incidents == null)
{
return NotFound();
}
return View(incidents);
}
// GET: Incidents/Create
public IActionResult Create()
{
return View();
}
// POST: Incidents/Create
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Event,NZDFMP,Incident,Location,Date_Time,Role,IncidentDetail,BOR,Action")] Incidents incidents)
{
if (ModelState.IsValid)
{
_context.Add(incidents);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(incidents);
}
// GET: Incidents/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var incidents = await _context.Incidents.FindAsync(id);
if (incidents == null)
{
return NotFound();
}
return View(incidents);
}
// POST: Incidents/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Event,NZDFMP,Incident,Location,Date_Time,Role,IncidentDetail,BOR,Action")] Incidents incidents)
{
if (id != incidents.IncidentId)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(incidents);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!IncidentsExists(incidents.IncidentId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(incidents);
}
// GET: Incidents/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var incidents = await _context.Incidents
.FirstOrDefaultAsync(m => m.IncidentId == id);
if (incidents == null)
{
return NotFound();
}
return View(incidents);
}
// POST: Incidents/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var incidents = await _context.Incidents.FindAsync(id);
_context.Incidents.Remove(incidents);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool IncidentsExists(int id)
{
return _context.Incidents.Any(e => e.IncidentId == id);
}
}
Класс ViewModel
public class ViewDetail
{
public Persons persons { get; set; }
public Incidents incidents { get; set; }
}
ViewDetailController
public class ViewDetailController : Controller
{
public IActionResult Index()
{
return View();
}
}