Click here to Skip to main content
15,888,286 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I successfully created a Job record using EF Core and ASP.NET 5 MVC. After hitting the create button a table list of unassignedUsers that DO NOT contain matching ID of the newly created record are supposed to appear but it won't.

Trying to do this in JobsController.GetUnassignedUsersJobId(int? ID).
Here is my code:

Views/Jobs/Create.cshtml

ASP
@model Pitcher.Models.Job
@{ 
    var user = new User();
}
@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>Job</h4>
<hr />
<div class="row">
    <div class="col-md-4">        
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="JobTitle" class="control-label"></label>
                <input asp-for="JobTitle" class="form-control" />
                <span asp-validation-for="JobTitle" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="JobDescription" class="control-label"></label>
                <textarea asp-for="JobDescription" class="form-control" rows="10" cols="50"></textarea>
                <span asp-validation-for="JobDescription" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="JobStartDate" class="control-label"></label>
                <input asp-for="JobStartDate" class="form-control" />
                <span asp-validation-for="JobStartDate" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="JobDeadline" class="control-label"></label>
                <input asp-for="JobDeadline" class="form-control" />
                <span asp-validation-for="JobDeadline" class="text-danger"></span>
            </div>
            <div class="form-group form-check">
                <label class="form-check-label">
                    <input class="form-check-input" asp-for="JobIsComplete" /> @Html.DisplayNameFor(model => model.JobIsComplete)
                </label>
            </div>
            <div class="form-group">
                <input type="submit" 
                value="Create" class="btn btn-primary" onclick='buttonClick()'/>
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@* Hide table before submission of record to DB *@
<table id="unassignedUsersTable" style='display:none;'>
<thead>
        <tr>
            <th>
               @Html.DisplayNameFor(model => user.UserFirstName)
            </th>        
            <th>
               @Html.DisplayNameFor(model => user.UserLastName)
            </th>
            <th>
               @Html.DisplayNameFor(model => user.UserContactEmail)
            </th>
            <th>                
            </th>
        </tr>
    </thead>
    <tbody></tbody>
</table>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    <script>
    $.fn.dataTable.ext.errMode = 'throw';
    //Reveal table if button click successful.  
    function buttonClick(){  
        document.getElementById('unassignedUsersTable').style.display = 'block'; 
        var id=@Model.ID
        $('#unassignedUsersTable').DataTable({
                "ajax": {
                type: 'get',
                'dataType': "json",
                //Get users from UsersController.                  
                "url": "@Url.Action("GetUnassignedUsersJobId")",
                "dataSrc": function (result) {
                    return result;
                    }
                },            
            "columns": [                
                { "data": "userFirstName"},
                { "data": "userLastName"},
                { "data": "userContactEmail"},
                {
                    "data": null,
                    "render": function (value) {
                        return '<a href="/Users/Details/' + value.id + '"button type="button" class="btn btn-primary btn-block">Details</a> <br> '
                            
                            + '<a href="/Users/Edit/' + value.id + '"button type="button" class="btn btn-info btn-block">Edit </a> <br> ' 
                            
                            + '<a href="/Users/Delete/' + value.id + '"button type="button" class="btn btn-primary btn-block">Delete</a>';
                    }
                }
                ]
        })
    };
        
    </script>
}


JobController
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Pitcher.Data;
using Pitcher.Models;
using Pitcher.Models.TeamViewModels;

namespace Pitcher.Controllers
{
    public class JobsController : Controller
    {
        private readonly TeamContext _context;

        public JobsController(TeamContext context)
        {
            _context = context;
        }

        public IActionResult GetUnassignedUsersJobId(int? ID)
        {
            //1.After creation of tblJob record.
            //2.SELECT all from tblUser Where most recently created tblJobId and
            //tblRegistration.UserID dos not match tblUserID
            //3.Display records
            _context.Jobs.OrderByDescending(j => j.ID).FirstOrDefault();
            var userlist = _context.Registrations.Where(r => r.UserID != r.User.ID).Select(r => r.User).ToList();            
            return Json(userlist);
        }

        // GET: Jobs/Create
        public IActionResult Create()
        {
            var job = new Job();
            return View(job);
        }

        // POST: Jobs/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        // COPY AND PASTE THIS METHOD CUSTOMIZATION INTO OTHER CONTROLLERS.  
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("JobTitle,JobDescription,JobStartDate,JobDeadline,JobIsComplete")] Job job)
        {
            try
            {
                if (ModelState.IsValid)
                {                    
                    _context.Add(job);
                    await _context.SaveChangesAsync();
                    // return RedirectToAction(nameof(Index));
                }
                    ViewData["Jobs"] = _context.Jobs.ToList();
            }
            catch(DbUpdateException /* ex */)
            {
                //Log the error (uncomment ex variable name and write a log).
                ModelState.AddModelError("", "Unable to save changes. " +
                "Try again, and if the problem persists " +
                "See your system administrator.");
            }
            return View(job);
        }


Job model
C#
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace Pitcher.Models
{
    public class Job
    {        
        
        public int ID { get; set; }

        [Required]
        [StringLength(20, MinimumLength = 3, ErrorMessage = "Job Title must be bettween 3 to 20 characters.")]
        [DataType(DataType.Text)]
        [Display(Name = "Job Title")]
        [Column("JobTitle")]
        public string JobTitle { get; set; }

        [StringLength(200, MinimumLength = 3, ErrorMessage = "Job Description must be bettween 200 to 3 characters.")]
        [DataType(DataType.Text)]
        [Display(Name = "Description")]
        [Column("JobDescription")]
        public string JobDescription { get; set; }

        [Required]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        [Display(Name = " Start Date")]
        [Column("JobStartDate")]
        public DateTime JobStartDate {get;set;}

        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        [Display(Name = "Deadline Date")]
        [Column("JobDeadlineDate")]
        public DateTime JobDeadline {get;set;}

        [Display(Name = "Job Is Complete?")]
        [Column("JobIsComplete")]
        public bool JobIsComplete{get;set;}

        public ICollection<Registration> Registrations {get;set;}

        public ICollection<Result> Results {get;set;}
    }   
}


Registration
C#
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace Pitcher.Models
{
    public class Registration
    {
        public int ID {get;set;}
        public int UserID { get; set; }
        public int JobID { get; set; }
        
        [Required]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        [Display(Name = "User Start Date")]
        [Column("RegistrationDate")]
        public DateTime RegistrationDate {get;set;}        
        public User User {get;set;}
        public Job Job {get;set;}
    }
}


User model
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Pitcher.Models;
namespace Pitcher.Models
{
    public class User
    {      
        public int ID { get; set; }

        [Required]
        [StringLength(20, MinimumLength = 2, ErrorMessage = "* First Name be bettween 2 to 20 characters.")]
        [DataType(DataType.Text)]
        [Display(Name = "First Name")]
        [Column("UserFirstName")]
        public string UserFirstName { get; set; }   

        [Required]
        [StringLength(30, MinimumLength = 2, ErrorMessage = "* Last Name be bettween 2 to 30 characters.")]
        [DataType(DataType.Text)]
        [Display(Name = "Last Name")]
        [Column("UserLastName")]
        public string UserLastName { get; set; }        
                
        [Required]
        [StringLength(30, MinimumLength = 3, ErrorMessage = "Email address must be bettween 3 to 30 characters.")]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email")]
        [Column("UserContactEmail")]
        public string UserContactEmail{get;set;}      
        
        // [Required(AllowEmptyStrings = true)]
        [Display(Name = "Phone Number")]
        [Phone()]
        [Column("UserPhoneNumber")]
        public string UserPhoneNumber{get;set;}
        
        [StringLength(37,ErrorMessage = "Address cannot be longer than 37 characters.")]
        [DataType(DataType.Text)]
        [Display(Name = "Address")]
        [Column("UserAddress")]
        public string UserAddress{get;set;}
        
        //This regular expression allows valid postcodes and not just USA Zip codes.        
        [Display(Name = "Post Code")]
        [Column("UserPostCode")][DataType(DataType.PostalCode)]
        public string UserPostCode { get; set; }

        [StringLength(15,ErrorMessage = "Country cannot be longer than 15 characters.")]
        [DataType(DataType.Text)]
        [Display(Name = "Country")]
        [Column("UserCountry")] 
        public string UserCountry {get;set;}
        
        
        [Phone()]
        [Display(Name = "Mobile Number")]
        [Column("UserMobileNumber")]
        public string UserMobileNumber {get;set;}

        [StringLength(3,ErrorMessage = "State cannot be longer than 3 characters.")]
        [DataType(DataType.Text)]
        [Display(Name = "State")]
        [Column("UserState")]
        public string UserState {get;set;}           
        
        public string UserFullname => string.Format("{0} {1}", UserFirstName, UserLastName);

        public ICollection<Registration> Registrations {get;set;}
    }
}


What I have tried:

I searched on Google and do not know how to do it.



These are the actions I'm trying to make occur.

1. Click 'submit'.

2. Select all of users who are capable of being assigned with this job.

3. Exclude the user who has been assigned with this kind of job from step1.

4. ASP generates an ID for the record (which it is successfully doing).

5. ASP Saves record to database (which it is successfully doing).

6. ASP then gets the most newly created record by ID. (I don't know how to do that.)

7. That ID will be stationed in memory and used to render the unassignedUsersTable to screen.
Posted
Updated 21-Mar-21 9:35am
v5
Comments
[no name] 21-Mar-21 10:15am    
Then you should just be focusing on the "query" (since you say everything else works), and not snow the rest of us under with irrelevant code.
Jordan Nash 21-Mar-21 15:45pm    
Shortened the question, by taking out irrelevant methods and class. I left the models as is as I am not sure they are irrelevant.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900