I am having an issue with my post-back from a DropDownList. I am trying to create a page which will allow users to create a new skillset, but the skillset links with skill categories, so I am using a DropDownList so that the user can select which category the skillset belongs to, but I am receiving this exception:
An exception of type 'System.ArgumentNullException' occurred in System.Web.Mvc.dll but was not handled in user code
Additional information: Value cannot be null.
This is my controllers for create:
// GET: SkillSets/Create
public ActionResult Create()
{
var categoryIDs = db.Categories.Where(c => c.Active == 1).Select(x => x.IDCategory).Distinct();
List<SelectListItem> items = new List<SelectListItem>();
foreach (var t in categoryIDs)
{
SelectListItem s = new SelectListItem();
s.Text = t.ToString();//db.Categories.Where(c => c.IDCategory == t & c.Active == 1).Select(x => x.Category + ": " + x.C_Role).Single();
s.Value = t.ToString();
items.Add(s);
}
ViewBag.Campaign = items;
return View();
}
// POST: SkillSets/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "IDSkillset,IDCategory,Product,P_Version,Notes")] Models.SkillSetsModel ss)
{
try
{
if (ModelState.IsValid)
{
db.SkillSets.Add(ss);
db.SaveChanges();
return RedirectToAction("Index");
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
And this is the DropDownList:
<div class="form-group">
@Html.LabelFor(model => model.IDCategory, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("Campaign", new SelectList(ViewBag.Campaign, "Value", "Text"), new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.IDCategory, "", new { @class = "text-danger" })
</div>
</div>
Here is the model:
namespace ITSSkillsDatabase.Models
{
[Table("SkillSets")]
public class SkillSetsModel
{
[Key]
public int IDSkillset { get; set; }
public int IDCategory { get; set; }
public string Product { get; set; }
[Display(Name = "Product Version")]
public string P_Version { get; set; }
public string Notes { get; set; }
public virtual ICollection<PersonSkillsModel> PersonSkills { get; set; }
}
}
The DropDownList works for the Get part of the create method, there just seems to be issues with either the view or the Post method, as the DropDownList is being populated.