locked
Passing list of values to View as part of model from partial class RRS feed

  • Question

  • User1047454725 posted

    I have an auto-generated class file produced as part of the Entity model. So I'm creating a partial class to keep my customizations there in order to keep from getting over-written. My purpose is to keep things like static drop-down value lists as part of the class file in order to consume them in the View.

    Auto-gen class:

    namespace CMECFDictionaryChanges.Models
    {
        using System;
        using System.Collections.Generic;
        
        public partial class Request
        {
            public Request()
            {
                this.AdminActions = new HashSet<AdminAction>();
            }
        
            public int Id { get; set; }
            public string RequestorName { get; set; }
            public System.DateTime RequestedOn { get; set; }
    ...

    Custom Partial Class:

    using System.Collections.Generic;
    
    namespace CMECFDictionaryChanges.Models
    {
        public partial class Request
        {
            private List<string> _changeTypeValues = new List<string> { "a", "b", "c" };
            
            public IEnumerable<string> ChangeTypeValues
            {
                get
                {
                    return _changeTypeValues;
                } 
            }
        }
    }

    The View:

    @model CMECFDictionaryChanges.Models.Request
    
    @{
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    ...
    
    @using (Html.BeginForm("CreateRequest", "User", FormMethod.Post))
    {
    ...
        <div class="row">
            <div class="col-xs-12 col-md-2">
                @Html.LabelFor(model => model.ChangeType, null, new { @class = "font-weight-bold" })
            </div>
            <div class="col-xs-12 col-md-4">
                @Html.DropDownListFor(model => model.ChangeType, new SelectList(Model.ChangeTypeValues), "Select", new { @class = "form-control" })
            </div>
        </div>
    }

    The problem is that the List defined in the partial class never gets initialized and as a result, you get the Object reference not set to an instance of an object error for the SelectList constructor. I'd rather avoid calling a method from the constructor of the auto-gen file to initialize the list because any customization in that file would be over-written.

    Is there a better way of achieving this? Thanks in advance.

     

    Wednesday, November 7, 2018 5:32 PM

All replies