0

I added the code to show many checkboxes from my table (HairTags) and in my form CreationUpload.cshtml i got the following error :

An exception of type 'System.NullReferenceException' occurred in App_Web eba142hb.dll but was not handled in user code Additional information: Object reference not set to an instance of an object.

Object reference not set to an instance of an object.

<div class="col-md-12">
                @for (int i = 0; i < Model.CreationHairTags.Count; i++)
                {
                    @Html.CheckBoxFor(m => Model.CreationHairTags[i].IsChecked)
                    @Model.CreationHairTags[i].Text
                    @Html.HiddenFor(m => Model.CreationHairTags[i].Value)
                    @Html.HiddenFor(m => Model.CreationHairTags[i].Text)<br />
                }
            </div>

this is my model Creation.cs (in bold the added code)

namespace HairCollection3.Models
{
    public class Creation
    {
        public string UserId { get; set; }
        [Key]
        public int CreationId { get; set; }

        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        [Display(Name = "Sex", ResourceType = typeof(ViewRes.Names))]
        public string CreationSex { get; set; }

        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        [Display(Name = "CreationTitle", ResourceType = typeof(ViewRes.NamesCreation))]
        [StringLength(2000)]
        [AllowHtml]
        public string CreationTitle { get; set; }


        public string CreationPhotoBis { get; set; }


        public string Creationtag { get; set; }        

        public virtual ICollection<CreationLike> CreationLikes { get; set; }

    }

    public class CreationLike
    {
        public int CreationId { get; set; }
        public string UserId { get; set; }
        public virtual ApplicationUser User { get; set; }
        [Key]
        public int CreationLikeId { get; set; }

        public virtual Creation ParentCreation { get; set; }

    }

    public class HairTag
    {
        [Key]
        public int HairTagId { get; set; }

        [Required]
        public string HairTagTitle { get; set; }

        [Required]
        public string HairTagType { get; set; }

        [Required]
        public int HairTagOrder { get; set; }

    }



    ***//CHECKBOXES
    public class HairTagModel
    {
        [Key]
        public int Value { get; set; }
        public string Text { get; set; }
        public bool IsChecked { get; set; }
    }

    public class HairTagList
    {
        private ApplicationDbContext creationdb = new ApplicationDbContext();

        public HairTagList()
        {
            var HairTagList = creationdb.HairTags.ToList();

            List<HairTagModel> obj = new List<HairTagModel>();
            foreach (var tags in HairTagList)
            {
                obj.Add(new HairTagModel
                {
                    Text = tags.HairTagTitle,
                    Value = tags.HairTagId,
                    IsChecked = false
                });
            }

            this.CreationHairTags = obj;
        }

        public List<HairTagModel> CreationHairTags { get; set; }

        //public List<HairTagModel> ListHairTags { get; set; }
    }

    public class CreationHairTagsModel
    {
        public Creation Creation { get; set; }
        public List<HairTagModel> CreationHairTags { get; set; }
    }


}***

My controller CreationController.cs

// GET: /Creation/CreationUpload
        [Authorize]
        public ActionResult CreationUpload()
        {
            CreationHairTagsModel creation = new CreationHairTagsModel();

            return View(creation);

            //return View();
        }

        // POST: /Creation/CreationUpload
        // Afin de déjouer les attaques par sur-validation, activez les propriétés spécifiques que vous voulez lier. Pour 
        // plus de détails, voir  http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [Authorize]
        [ValidateAntiForgeryToken]
        public ActionResult CreationUpload([Bind(Include = "CreationId,CreationSex,CreationTitle,CreationPhotoBis,CreationHairTags")] CreationHairTagsModel creation, IEnumerable<HttpPostedFileBase> files)
        {
            if (ModelState.IsValid)
            {


                // update each field manually
                foreach (var file in files)
                {
                    if (file != null)
                    {
                        if (file.ContentLength > 0)
                        {

                           ....CODE UPLOAD HIDDEN....

                                //Avoid Script
                                var CreationTitletocheck = Regex.Replace(creation.Creation.CreationTitle, @"<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>", string.Empty);
                                CreationTitletocheck = Regex.Replace(CreationTitletocheck, @"(?></?\w+)(?>(?:[^>'""]+|'[^']*'|""[^""]*"")*)>", string.Empty);
                                creation.Creation.CreationTitle = CreationTitletocheck;

                                //Tags
                                StringBuilder sb = new StringBuilder();
                                foreach (var item in creation.CreationHairTags)
                                {
                                    if (item.IsChecked)
                                    {
                                        sb.Append(item.Text + ",");
                                    }
                                }
                                creation.Creation.Creationtag = sb.ToString();

                                creation.Creation.UserId = User.Identity.GetUserId();


                                db.Creations.Add(creation.Creation);
                                db.SaveChanges();



                            }


                        }
                    }
                }

                //UserId
                return RedirectToAction("CreationList", "Creation", new { UserId = User.Identity.GetUserId() });
            }

            return View(creation);
        }

My page of upload CreationUpload.cshtml

@model HairCollection3.Models.CreationHairTagsModel
@using Microsoft.AspNet.Identity


@{
    ViewBag.Title = ViewRes.NamesCreation.CreationUploadTitle;
}


<div class="col-sm-12 col-md-12 chpagetop">

    <h1>@ViewRes.Shared.PublishAPhoto</h1>

    <hr />

    @using (Html.BeginForm("CreationUpload", "Creation", FormMethod.Post, new { id = "CreationUpload", enctype = "multipart/form-data", onsubmit = "$('#creationloading').show(); $('#creationform').hide();" }))
    {
        @Html.AntiForgeryToken()


        <div class="col-md-12" id="creationloading" style="display:none">
            <div id="progress">
                <p>@ViewRes.Shared.UploadPhotoProgress<strong>0%</strong></p>
                <progress value="5" min="0" max="100"><span></span></progress>
            </div>
        </div>

        <div class="col-md-12" id="creationform">

            <div class="col-md-12">
                @Html.ValidationMessageFor(m => m.Creation.CreationSex)
                @Html.RadioButtonFor(m => m.Creation.CreationSex, "F", new { @checked = true }) @ViewRes.Shared.WomanHairstyle  @Html.RadioButtonFor(m => m.Creation.CreationSex, "M") @ViewRes.Shared.ManHairstyle
            </div>

            <div class="col-md-12">
                @Html.ValidationMessageFor(m => m.Creation.CreationTitle)
                @Html.TextBoxFor(m => m.Creation.CreationTitle, new { @class = "inputplaceholderviolet wid100x100", placeholder = HttpUtility.HtmlDecode(Html.DisplayNameFor(m => m.Creation.CreationTitle).ToHtmlString()), onfocus = "this.placeholder = ''", onblur = "this.placeholder = '" + HttpUtility.HtmlDecode(Html.DisplayNameFor(m => m.Creation.CreationTitle).ToHtmlString()) + "'" })
            </div>

            <div class="col-md-12">
                @for (int i = 0; i < Model.CreationHairTags.Count; i++)
                {
                    @Html.CheckBoxFor(m => Model.CreationHairTags[i].IsChecked)
                    @Model.CreationHairTags[i].Text
                    @Html.HiddenFor(m => Model.CreationHairTags[i].Value)
                    @Html.HiddenFor(m => Model.CreationHairTags[i].Text)<br />
                }
            </div>

            <div class="col-md-12" style="text-align: center">
                <p style="display: inline-block">
                    <input type="file" accept="image/*" onchange="loadFile(event)" name="files" id="file1" translate="yes" data-val="true" data-val-required="A File is required." class="wid100x100" /><label for="file1"></label>
                <img id="output" style="max-width:200px;"/>
        </p>
            </div>

            <div class="col-sm-12 col-md-12 chpagetopdiv">
                <button type="submit" title="@ViewRes.Shared.Publish"><span class="glyphicon glyphicon-share-alt"></span> @ViewRes.Shared.Publish</button>
            </div>

        </div>

    }


</div>

What is wrong in my code please help and explain ?

Alexey Zimarev
  • 17,944
  • 2
  • 55
  • 83
  • 1
    Null reference is one of the most commonly mentioned error types on this site. Unfortunately, it is also an error that can only be sorted out through debugging, not code analysis. – Claies Mar 30 '16 at 14:22

1 Answers1

0

Important: In C#, every collection must be initialized before being accessed

The error occurs when you are trying to access from the View to the collection CreationHairTags, which is not initialized. Replace your model to initialize collection in the class constructor:

public class CreationHairTagsModel
{
    public Creation Creation { get; set; }
    public List<HairTagModel> CreationHairTags { get; set; }

    public CreationHairTagsModel()
    {
        CreationHairTags = new List<HairTagModel>();
    }
}
Balde
  • 590
  • 3
  • 8
  • Hi, thanks for your answer, in fact yesterday i resolved this problem, but now i do have another probelm coming out.. i post it here : http://stackoverflow.com/questions/36337946/model-called-inside-another-model-result-null-when-form-post-and-modelstate-vali if you are so kind to look at it and see if you could tell me what the probelm is.. thanks – Carles Amnesty Mar 31 '16 at 15:43