0

t is very strange, all works fine,

i show all my textboxes in my form, all my checkboxes, but when i send my form i got error in my controller on the first of my string example :

creation.Creation.CreationPhotoBis = fileName200;

It is telling me that creation.Creation.CreationPhotoBis is NULL

StackTrace :

   à HairCollection3.Controllers.CreationController.CreationUpload(CreationHairTagsModel creation, IEnumerable`1 files) dans c:\FRANCESCO\Project\HairCollection3\HairCollection3\Controllers\CreationController.cs:ligne 650
   à lambda_method(Closure , ControllerBase , Object[] )
   à System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
   à System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
   à System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   à System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod()
   à System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__36(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
   à System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
   à System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   à System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
   à System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
   à System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3c()
   à System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass45.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3e()

Error :

{"Object reference not set to an instance of an object."}

InnerEception : Creation

null

In fact in my model CreationHairTagsModel the model Creation is = Null!!! why?

whot do i need to fix it?

Here my model Creation.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HairCollection3.Models
{
    public class Creation
    {
        public string UserId { get; set; }
        [Key]
        public int CreationId { get; set; }
        public string CreationLanguage { 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 bool CreationVisible { get; set; }
        public bool CreationDelete { get; set; }
        public DateTime CreationDate { get; set; }
        public string CreationIpAdress { get; set; }

        public string CreationPhotoBis { get; set; }
        public string CreationPhoto750 { get; set; }
        public string CreationPhotoReal { 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 DateTime CreationLikeDate { get; set; }
        public string CreationLikeIpAdress { 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 HairTagTitleEN { get; set; }
        [Required]
        public string HairTagTitleIT { get; set; }
        [Required]
        public string HairTagTitleSP { 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; }

        public Creation Creation { get; set; }

        private ApplicationDbContext creationdb = new ApplicationDbContext();

        public List<HairTagModel> CreationHairTags
        {
            get
            { 
                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
                    });
                }

                return obj;
            }
        }
    }


}

Here 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)
                        {

                                     ...UPLOAD CODE HIDDEN                           
                                    creation.Creation.CreationPhotoBis = fileName200;


                                //Ipaddress
                                var ipAddress = Request.ServerVariables["REMOTE_ADDR"];

                                //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();
                                creation.Creation.CreationLanguage = ViewRes.Shared.Langue;
                                creation.Creation.CreationVisible = true;
                                creation.Creation.CreationDelete = false;
                                creation.Creation.CreationDate = DateTime.Now;
                                creation.Creation.CreationIpAdress = ipAddress;
                                creation.Creation.CreationPhotoReal = fileName; //after add

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



                            }


                        }
                    }
                }

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

            return View(creation);
        }

here my view : 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>

In my IdentityModels.cs

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Web.Mvc;

namespace HairCollection3.Models
{
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    public class ApplicationUser : IdentityUser
    {

        // New Fields added to extend Application User class:
        CODE USER HIDDEN

    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }



        public DbSet<Creation> Creations { get; set; }
        public DbSet<CreationLike> CreationLikes { get; set; }
        public DbSet<HairTag> HairTags { get; set; }        

What is wrong in my code please help and explain ?

1 Answers1

1

When CreationHairTagsModel is instantiated by ModelBinding the Creation property is null.

Try initializing Creation property in the CreationHairTagsModel constructor so that when ModelBinding creates CreationHairTagsModel, Creation will not be null.

public CreationHairTagsModel()
{
    Creation = new Creation();
}
Andy T
  • 10,223
  • 5
  • 53
  • 95
  • Hi, i added your code and now this error is gone, THANKS!! But now i do have another error, when i send the form all the value are = NULL like this one : creation.Creation.CreationTitle you can find this in my controller here : `code`var CreationTitletocheck = Regex.Replace(creation.Creation.CreationTitle, @" – Carles Amnesty Mar 31 '16 at 16:05
  • @CarlesAmnesty remove `Bind(Include = "CreationId,CreationSex,CreationTitle,CreationPhotoBis,CreationHairTags")]` in post versión of `CreationUpload`. Additionally, I recommend you to make a simpliest `ViewModel` version of `CreationHairTagsModel`, containing only properties you will use inside the View, and this way, avoid to instantiate `Creation` when you only need a few properties of it. – Balde Mar 31 '16 at 16:37
  • Hi, if i take of the BIND code i got the same error.. all the values coming from my form are empty = NULL, i saw somewhere that we can add in our model something like this : this.Creation.CreationTitle = Creation.CreationTitle; but i am a beginner i do not know how to do this .. – Carles Amnesty Mar 31 '16 at 16:49
  • This has nothing to do with it. The `DefaultModelBinder` will initialize any properties which are models if a a value of that model is posted (which is happening) - adding a constructor is not necessary. The reason binding is failing is that the model contains a property named `creation` and the parameter in the POST method is also named `creation` –  Mar 31 '16 at 21:54
  • Thanks @Stephen Muecke, i followed your instruction, i took off the "Bind code" and changed in my controller creation to creationbind, and now is working!!Little by little i am learning.. but still i have another problem.. My checkboxes results null even if i check some of them and in my controller i did debug in my line : 'foreach (var item in creationbind.CreationHairTags)' an all the value are = NULL but i choose 2 of them? Based on my code, do you know what is wrong? Thanks again for your help – Carles Amnesty Apr 01 '16 at 07:51