0

I am getting error of "system.nullreferenceexception object reference not set to an instance of an object" while storing ID of dropdown list. I have gone through many sites and posts but still I am stuck in this error. Please help me to solve this error.

Model:

  [Required]
    [Display(Name = "Profession")]
    public virtual string professionid { get; set; }
    IEnumerable<SelectListItem> professionList = new List<SelectListItem>();
    public SelectList getProfession()
    {

        professionList = (from m in _db.ProfessionInfos select m).AsEnumerable().Select(m => new SelectListItem() { Text = m.P_Name, Value = m.P_id.ToString() });
        return new SelectList(professionList, "Value", "Text", professionid);
    }

Controller:

[HttpGet]
    public ActionResult Registration()
    {
        var model = new M_Reg();
        return View(model);
    }

View:

 <div class="editor-label">
            @Html.LabelFor(m => m.professionid)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(m => m.professionid,Model.getProfession(),"Choose Profession")
            @Html.ValidationMessageFor(m => m.professionid)
        </div>
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Saurabh Gadariya
  • 191
  • 6
  • 20
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Mar 12 '14 at 12:51

1 Answers1

0

Add one more property to your model of type SelectList ProfessionIds

and set value to this property on you controller like :

model.ProfessionIds=model.getProfession(); now you can use it on your view like : @Html.DropDownListFor(m => m.professionid,Model.ProfessionIds,"Choose Profession")

Or the second way is to use ViewBag to simply pass ProfessionIds from controller to view :

Your Controller's Action Method will look like :

var model = new M_Reg();
ViewBag.Ids=model.getProfession();
return View(model);

And on your view use

@Html.DropDownListFor(m => m.professionid,(Selectlist)ViewBag.Ids,"Choose Profession")

Abhay Prince
  • 2,032
  • 1
  • 15
  • 17
  • thanks Abhay for answer, but unfortunately both the things are not working in this case. Dropdown ids are stored in database but it is giving me this error – Saurabh Gadariya Mar 12 '14 at 14:50