模型中的 MVC 显示变量

Posted

技术标签:

【中文标题】模型中的 MVC 显示变量【英文标题】:MVC Display Variables from Model 【发布时间】:2015-02-19 15:30:40 【问题描述】:

我很难弄清楚如何显示在我的“模型”文件中设置的变量(然后在我的“视图”文件中的“服务”文件中填充。 学生信息模型:

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; 
    

学生信息服务:

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;
        
    

信息(视图):

@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>

我的控制器是:

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 );
            
        
    

所以我要做的是将“Birthdate”“EnrollmentType”等变量放在不是 DataTables 的表中(“General”、“enrollmentInfo”等),因此它将显示为示例:

生日: 1994 年 4 月 29 日

那么如何引用和显示这些变量呢? 谢谢!

【问题讨论】:

【参考方案1】:

从您的角度来看,假设它是剃须刀,您只需执行以下操作:

Birthdate: @Model.Birthdate

要初始化您的服务,您可以在控制器中使用依赖注入。

这将涉及:

选择和安装 DI 容器 在您的控制器上创建一个接受服务并将其分配给只读变量的构造函数

如果不查看您的控制器代码或不知道您使用的是哪个 DI,很难给出具体示例。

值得阅读以下示例,该示例显示了如何做到这一点的基础知识。

MSDN dependency injection article

ps 你不需要以这种方式创建构造函数。

您可以简单地使用初始化器创建 StudentInfo 对象,如下所示(添加所有需要的字段):

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

MSDN object initializer reference

更新

我将把它简化成简短的例子。

首先,我会重构您的服务以删除您不需要的静态方法和字段。只需让您的方法返回集合即可。

为您的服务提取一个接口,即IStudentInfoService 公开方法。

向控制器添加一个构造函数,将服务注入其中。

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);
    

最后安装一个 DI 并设置引导程序(Unity 的步骤在上面的文章中)。

【讨论】:

这给了我一个“System.NullReferenceException”。附加信息是:“对象引用未设置为对象的实例。” @JosiahNusbaum 我添加了一个注释和文章,它将为您指明正确的方向。祝你好运。 :) 好的,谢谢!我应该添加控制器,我的错!如果可以帮助您更具体地举例说明,我将其添加到原始帖子中?我正在努力理解注入文章,但我从查看示例中学到了更好的东西!感谢您的帮助,非常感谢! 好的,我想我明白了!当我们将它连接到数据库而不是通过服务文件填充数据时,这应该可以工作,对吗?数据库还没有准备好连接,所以我们现在使用服务人口作为占位符并用于测试目的。 @josiah-nusbaum 是的,取决于您的设计。对于数据库实现,您可以创建接口的另一个具体实例并通过 DI 引导程序将其换出。您可能希望将数据库访问权移至存储库并将其也注入您的服务中。取决于您的最终设计。

以上是关于模型中的 MVC 显示变量的主要内容,如果未能解决你的问题,请参考以下文章

ASP.Net MVC:如何显示模型中的字节数组图像

PHP MVC 最佳实践 - 将 Session 变量从控制器传递给模型类或直接在模型中访问

TableviewCell 中的 CollectionView :使用 Alamofire 和 SwiftyJSON 和 MVC 模型显示数据

MVC 模型:赋值的左侧必须是变量、属性或索引器

MVC 模型布尔显示是或否

使用 C# 计算 MVC 模型中的时间跨度