0

I am new to ASP.NET MVC and I'm working on my first project just for fun. I get this ArgumentNullException and I cannot figure out what's wrong.

This is my model:

public class SpeciesLabel
{
    [Key]
    [Required]
    public string Name { get; set; }

    [Required]
    public CustomGroup CustomGroup { get; set; }

    [Required]
    public Family Family { get; set; }

    [Required]
    public Genus Genus { get; set; }

    [Required]
    public Species Species { get; set; }
}

public class SpeciesLabelDbContext : DbContext
{
    public SpeciesLabelDbContext()
        : base("DefaultConnection")
    {

    }

    public DbSet<SpeciesLabel> SpeciesLabel { get; set; }
}

This is the controller:

 public ActionResult Create()
    {
        List<SelectListItem> customGroups = new List<SelectListItem>();
        IQueryable<string> customGroupsQuery = from g in customGroupsDb.CustomGroup
            select g.Name;

        foreach (var element in customGroupsQuery)
        {
            customGroups.Add(new SelectListItem()
            {
                Value = element,
                Text = element
            });
        }

        ViewBag.CustomGroup = customGroups;

This is the controller POST request:

public ActionResult Create([Bind(Include = "CustomGroup,Family,Genus,Species")] SpeciesLabel speciesLabel)
    {
        if (ModelState.IsValid)
        {
            db.SpeciesLabel.Add(speciesLabel);
            db.SaveChanges();
            return RedirectToAction("Create");
        }

        return View();
    }

And this is the view:

    <pre>
        @model PlantM.Models.PlantModels.SpeciesLabel

@{
    ViewBag.Title = "Create";
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Species label</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.CustomGroup, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.CustomGroup, new SelectList(ViewBag.CustomGroupList, "Value", "Text"), "Please select...", new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.CustomGroup, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}
</pre>

I have inputs for all properties in the view but I cut them as they are similar to this one and the exception would be the same. Only property Name is not returned from the view as it will be designed in the controller (concatenation of the other properties).

This is the exception I get when I submit the form:

ArgumentNullException

Edit:

After adding the ViewBag initialization in the POST Create method the problem with the ArgumentNullException is resolved but I still receive Null value arguments and the object cannot be created due to this and the Create view is recalled again and again!? Can anyone advise why these @Html.DropDownListFor do not post any value to the controller?

  • Are you saying that `ViewBag.CustomGroupList` is NULL? – pookie Jul 26 '17 at 16:01
  • Well, I think it is not null because I see the list in the dropdown menu but when I select an option and I click the submit button I get this exception. I guess there is a problem with sending the data back to the controller but I don't know what's wrong. – Marian Jordanov Jul 26 '17 at 16:04
  • Put [HttpPost] above your create action? – pookie Jul 26 '17 at 16:10
  • It is there I just skipped the lines. Here is the complete solution https://github.com/MJordanov81/PlantM – Marian Jordanov Jul 26 '17 at 16:14
  • Okay, can you tell us exactly which line is throwing the exception? – pookie Jul 26 '17 at 16:39
  • Since this question has been resolved, I would create a new question rather than update this one. I don't think people will pay attention to it if it has been marked as "resolved". – pookie Jul 26 '17 at 19:32
  • There are multiple problems with this code, and you have not even shown the correct code. You cannot bind a ` –  Jul 26 '17 at 23:51
  • The error message means that the value of `ViewBag.CustomGroupList` is `null`. You have not set it's value in either the GET method or the POST method. I recommend you read [this question/answer](https://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of-type-system-int32-but-must-be-o). The answer you have accepted is a awful hack that solves your immediate issue but and results in other errors. Your editing data so **always** use a view model. –  Jul 26 '17 at 23:53

1 Answers1

0

From the comment, it sound like you see the view on first visit, but a null exception happen after you post.

If above assumption is correct, then I think your problem is because when you post back, your model did not pass the validation (for example, maybe a required input field did not post back value), which means ModelState.IsValid is false, so return View() was called

Here is the problem, you are not setting the ViewBag.CustomGroup = customGroups; in before return, hence ViewBag.CustomGroup is null, that is why you are seeing the exception.

init the ViewBag like how you did it on get then you should be able to see the page.

Alan Tsai
  • 2,465
  • 1
  • 13
  • 16
  • Thanks, that worked! Probably the state is not valid because I do not return one of the properties which is required because I wanted to create it in the controller as concatination of some of the returned properties. Probably I should reconsider this. Thank you once again! – Marian Jordanov Jul 26 '17 at 16:48
  • I still have an issue I cannot resolve. Could you please see the edit of my post above? Thank you! – Marian Jordanov Jul 26 '17 at 17:23
  • @MarianJordanov it would be best to create another question for better visibility - but you would have to provide more description. such as which line did the error happen? did it happen at get or post? I will be happy to provide some answer if you describe the problem more detail – Alan Tsai Jul 27 '17 at 01:23