1

I'm having a hard time figuring out how to display a variable set up in my "Model" file (and then populated in my "Service" file in my "View" file. StudentInfoModel:

using System;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Globalization;

namespace SAAS.Models
{
    public class StudentInfo
    {
        public StudentInfo(int studentID, string name, string ssan, DateTime birthdate, string address, string homePhone, string enrollmentType, string diplomaGED, string cellPhone, string sex, string race, string altName, string altRelation, string altPhone, string altAddress, DateTime altDateUpdated, string altUpdatedBy, string payStatus, string regionalWaiver, string previousResident, DateTime lastStatusChange, DateTime enrollmentDate, DateTime actEnrollmentDate, DateTime arrivalDate, DateTime atEnrollmentDate, string gedStatus, string gedState, DateTime gedDate, string vocationStatus, DateTime separationDate, string sepAddress, string sepPhone)
        {
            StudentID = studentID;
            Name = name;
            SSAN = ssan;
            Birthdate = birthdate.ToString("dd MMMM yyyy", CultureInfo.InvariantCulture);
            Address = address;
            HomePhone = homePhone;
            EnrollmentType = enrollmentType;
            DiplomaGED = diplomaGED;
            CellPhone = cellPhone;
            Sex = sex;
            Race = race;
            AltName = altName;
            AltRelation = altRelation;
            AltPhone = altPhone;
            AltAddress = altAddress;
            AltDateUpdated = altDateUpdated.ToString("dd-MMMM-yyyy", CultureInfo.InvariantCulture);
            AltUpdatedBy = altUpdatedBy;
            PayStatus = payStatus;
            RegionalWaiver = regionalWaiver;
            PreviousResident = previousResident;
            LastStatusChange = lastStatusChange.ToString("dd MMMM yyyy", CultureInfo.InvariantCulture);
            EnrollmentDate = enrollmentDate.ToString("dd MMMM yyyy", CultureInfo.InvariantCulture);
            ActEnrollmentDate = actEnrollmentDate.ToString("dd MMMM yyyy", CultureInfo.InvariantCulture);
            ArrivalDate = arrivalDate.ToString("dd MMMM yyyy", CultureInfo.InvariantCulture);
            AtEnrollmentDate = atEnrollmentDate.ToString("dd MMMM yyyy", CultureInfo.InvariantCulture);
            GedStatus = gedStatus;
            GedState = gedState;
            GedDate = gedDate.ToString("dd MMMM yyyy", CultureInfo.InvariantCulture);
            VocationStatus = vocationStatus;
            SeparationDate = separationDate.ToString("dd MMMM yyyy", CultureInfo.InvariantCulture);
            SepAddress = sepAddress;
            SepPhone = sepPhone;
        }

        [Key]
        public int StudentID { get;set; }
        public string Name { get; set; }
        public string SSAN { get; set; }
        public string Birthdate { get;set; }
        public string Address { get;set; }
        public string HomePhone { get;set; }
        public string EnrollmentType { get;set; }
        public string DiplomaGED { get;set; }
        public string CellPhone { get;set; }
        public string Sex { get; set; } 
        public string Race { get;set; }
        public string AltName { get;set; }
        public string AltRelation { get;set; }
        public string AltPhone { get;set; }
        public string AltAddress { get;set; }
        public string AltDateUpdated { get;set; }
        public string AltUpdatedBy { get;set; }
        public string PayStatus { get;set; }
        public string RegionalWaiver { get;set; }
        public string PreviousResident { get;set; }
        public string LastStatusChange { get;set; }
        public string EnrollmentDate { get;set; }
        public string ActEnrollmentDate { get;set; }
        public string ArrivalDate { get;set; }
        public string AtEnrollmentDate { get;set; }
        public string GedStatus { get;set; }
        public string GedState { get;set; }
        public string GedDate { get;set; }
        public string VocationStatus { get;set; }
        public string SeparationDate { get;set; }
        public string SepAddress { get;set; }
        public string SepPhone { get;set; }
    }
}

StudentInfoService:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SAAS.Models;

namespace SAAS.Services
{
    public class StudentInfoService
    {
        private static readonly List<StudentInfo> StudentInfos;

        static StudentInfoService()
        {
            StudentInfos = new List<StudentInfo>
            {
                new StudentInfo(87654321, "John Doe", "123-45-6789", new DateTime(1986, 3, 29), "1234 Oak Street, Destin, FL", "(210) 555-1212", "O", "Y", "(210) 555-1212", "M", "W", "Joyce Doe", "Mother", "610-555-5555", "123 Magnolia St., Biloxi, MS 21818", new DateTime(2014, 9, 28), "Spacely Sprocket", "1-Normal", "N", "N", new DateTime(2014, 9, 18), new DateTime(2014, 4, 15), new DateTime(2014, 4, 15), new DateTime(2014, 4, 15), new DateTime(2014, 4, 15), "Passed", "NY", new DateTime(2013, 2, 3), "3 Trainee", new DateTime(2014, 12, 12), "123 Maple St., Apt 62, Anytown, NY 12345", "(555) 555-1111")
            };
        }

        public List<StudentInfo> GetStudentInfos(int start, int length)
        {
            return FilterStudentInfo().Skip(start).Take(length).ToList();
        }

        public int Count()
        {
            return FilterStudentInfo().Count();
        }

        public IQueryable<StudentInfo> FilterStudentInfo()
        {
            IQueryable<StudentInfo> results = StudentInfos.AsQueryable();
            return results;
        }
    }
}

Info (the View):

@model SAAS.Models.StudentInfo
<link href="~/Content/info.css" rel="stylesheet" />
@{
    ViewBag.Title = "Student - Info";
    ViewBag.SubTitle = "General Info";
}

@Html.Partial("_StudentNavPartial")
@Html.Partial("_StudentSearchBar")
<div class="container-fluid left">
    <h4>@ViewBag.SubTitle</h4>
<div class="outline">
    <table id="General" class="borderless">
        <tr>
            <td><strong>Birthdate: </strong></td>
            <td><strong>Enrollment Type: </strong></td>
            <td><strong>Sex: </strong></td>
            <td><strong>Race: </strong></td>
        </tr>
        <tr>
            <td><strong>Address: </strong></td>
            <td><strong>Diploma/GED: </strong></td>
        </tr>
        <tr>
            <td><strong>Home Phone: </strong></td>
            <td><strong>Cell Phone: </strong></td>
        </tr>
    </table>
    <br />
    <h5>Alternate Addresses</h5>
    <table id="AlternateAddresses" class="table table-striped table-bordered table-hover text-nowrap">
        <thead>
            <tr>
                <th data-column="AltName" class="text-center" id="TDtooltip" data-toggle="tooltip" data-placement="bottom" data-original-title="Alternate Contact Name" data-container="body">Contact Name</th>
                <th data-column="AltRelation" class="text-center" id="TDtooltip" data-toggle="tooltip" data-placement="bottom" data-original-title="Alternate Contact Relation" data-container="body">Relation</th>
                <th data-column="AltPhone" class="text-center" id="TDtooltip" data-toggle="tooltip" data-placement="bottom" data-original-title="Alternate Contact Phone Number" data-container="body">Phone</th>
                <th data-column="AltAddress" class="text-center" id="TDtooltip" data-toggle="tooltip" data-placement="bottom" data-original-title="Alternate Contact Address" data-container="body">Address</th>
                <th data-column="AltDateUpdated" class="text-center" id="TDtooltip" data-toggle="tooltip" data-placement="bottom" data-original-title="Date Alternate Contact Updated" data-container="body">Date Updated</th>
                <th data-column="AltUpdatedBy" class="text-center" id="TDtooltip" data-toggle="tooltip" data-placement="bottom" data-original-title="Who Updated Alternate Contact Information" data-container="body">Updated By</th>
            </tr>
            </thead>
    </table>
    </div>
    <br />
    <h4>Enrollment Info</h4>
    <div class="outline">
        <table id="enrollmentInfo" class="borderless">
            <tr>
                <td><strong>Student Pay Status: </strong></td>
                <td><strong>Date Status Last Change: </strong></td>
                <td></td>
            </tr>
            <tr>
                <td><strong>Regional Waiver: </strong></td>
                <td><strong>Enrollment Date: </strong></td>
                <td><strong>Arrival Date: </strong></td>
            </tr>
            <tr>
                <td><strong>Previous Resident: </strong></td>
                <td><strong>ACT Enrollment Date: </strong></td>
                <td><strong>AT Enrollment Date: </strong></td>
            </tr>
        </table>
        <br />
        <h5>Education</h5>
        <table id="education">
            <tr>
                <td><strong>GED Status: </strong></td>
                <td><strong>GED State: </strong></td>
                <td><strong>GED Date: </strong></td>
                <td><strong>Vocation Status: </strong></td>
            </tr>
        </table>
        <br />
        <h5>Separation</h5>
        <table id="separation">
            <tr>
                <td><strong>Date: </strong></td>
                <td><strong>Address: </strong></td>
                <td><strong>Phone: </strong></td>
            </tr>
        </table>
    </div>
</div>

@section scripts
{
    @Scripts.Render("~/bundles/dataTables")
<script type="text/javascript">

    $.extend($.fn.dataTable.defaults, {
            'pagingType': 'full_numbers',
            'pageLength': 2,
            'language': {
                'paginate': {
                    'first': '&laquo;',
                    'last': '&raquo;',
                    'previous': '&lsaquo;',
                    'next': '&rsaquo;'
                },
            },
            //'dom': '<"top"f>rt<"bottom"<"pull-left"l><"pull-right"i>p<"clear">>',
            'dom': '<"top">rt<"bottom"<"pull-left"><"pull-right"><"clear">>',
            'initComplete': function (settings, json) {
                $('.dataTables_filter input[type=search]').attr('placeholder', 'Search');
            }
        });
    $('#AlternateAddresses').dataTable({
        'ajax': {
            type: 'POST',
            url: '@Url.Action("GetData", "StudentInfo")',
            //data: function(d) {
            //}
            "bPaginate": false,
        },
        columns: [
            {
                data: 'AltName',
                sortable: true,
                className: "text-left"
            },
            {
                data: 'AltRelation',
                sortable: true,
                className: "text-left"
            },
            {
                data: 'AltPhone',
                sortable: true,
                className: "text-left"
            },
            {
                data: 'AltAddress',
                sortable: true,
                className: "text-left"
            },
            {
                data: 'AltDateUpdated',
                sortable: true,
                className: "text-left"
            },
            {
                data: 'AltUpdatedBy',
                sortable: true,
                className: "text-left"
            }
        ],
        //jQueryUI: true,
        sort: true,
        ordering: true,
        order: [0, 'AltName'],
        processing: true,
        serverSide: true
    });
    $('[data-toggle="tooltip"]').tooltip({
        delay: 0,
        track: true,
        fade: 100
    });
    </script>
}

My Controller is:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using SAAS.Models;
using SAAS.Services;

namespace SAAS.Controllers
{
    public class StudentInfoController : Controller
    {

        // GET: StudentInfo
        public ActionResult Info()
        {
            return View();
        }

        public JsonResult GetData(DTParameters dtModel, FilterViewModel filterModel)
        {
            try
            {
                List<StudentInfo> data = new StudentInfoService().GetStudentInfos(dtModel.Start, dtModel.Length);
                int count = new StudentInfoService().Count();
                DTResult<StudentInfo> result = new DTResult<StudentInfo>
                {
                    draw = dtModel.Draw,
                    data = data,
                    recordsFiltered = count,
                    recordsTotal = count
                };
                return Json(result);
            }
            catch (Exception ex)
            {
                return Json(new { error = ex.Message });
            }
        }
    }
}

So what I'm trying to do is put the "Birthdate" "EnrollmentType", etc variables in the tables that aren't DataTables ("General", "enrollmentInfo", etc), so it will display as, for example:

Birthdate: 4/29/1994

So how do I reference and display these variables? Thanks!

1 Answer 1

1

From within your view assuming it is razor you would simply do the following:

Birthdate: @Model.Birthdate

To initialize your service you could use dependency injection within your controller.

This would involve:

  • Choosing and installing a DI container
  • Creating a constructor on your controller that accepts the service and assigns it to a readonly variable

Without seeing your controller code or knowing which DI you are taking it is difficult to give a concrete example.

It is worth having a read of the following example which shows the basics of how to do exactly that.

MSDN dependency injection article

ps You don't need to create the constructor in that manner.

You can simply create the StudentInfo object with initializers as follows (adding all the fields needed):

new StudentInfo { StudentID = 1, Name = "A Name" };

MSDN object initializer reference

Update

I will simplify this into short examples.

First I would refactor your service to remove the static methods and fields as you don't need them. Just have your methods return collections.

Extract an interface for your service i.e. IStudentInfoService exposing the methods.

Add a constructor to your controller that injects the service into it.

public class StudentInfoController : Controller
{
private readonly IStudentInfoService _studentService;

    public StudentInfoController(IStudentInfoService studentService)
    {
      _studentService = studentService;
    } 

    // GET: StudentInfo
    public ActionResult Info()
    {
        var model = _studentService.FilterStudentInfo();
        return View(model);
    }

Finally install a DI and setup the bootstrapper (the steps for Unity are in the article above).

Sign up to request clarification or add additional context in comments.

5 Comments

that gives me a 'System.NullReferenceException'. The additional information is: "Object reference not set to an instance of an object."
@JosiahNusbaum I've added a note and article that will point you in the right direction. Good luck. :)
Okay, thanks! I should have added the Controller, my fault! I added it to the original post if that could help you be more specific example-wise? I'm working on understanding the injection article, but I learn better from seeing examples! Thanks for your help, it's really appreciated!
Okay, I think i get it! This should work when we connect it to the database instead of populating the data through the Services file, correct? The database isn't ready to be connected yet, so we're using the Services population as a placeholder and for testing purposes for now.
@josiah-nusbaum yes, depending on your design. For the database implementation you could just create another concrete instance of the interface & have it swapped out via the DI bootstrapper. You may want to move db access to a repository & inject that into your service too. Depending on your final design.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.