1

I am still struggling with learning ASP.NET MVC. All my form entries are required so I would like to do validation on them. For brevity I have paired my model down to Description (textbox) and Paradigm (dropdown). I am including Entry.cs, Paradigm.cs and EntryViewModel.cs Model classes and the Display.cshtml View.

[Bind(Exclude = "EntryId")]
public class Entry
{
  [ScaffoldColumn(false)] 
  public int EntryId { get; set; }

  [Required(ErrorMessage = "You must include a description.")]
  public string Description { get; set; }

  [Display(Name = "Type")]
  [Required(ErrorMessage = "You must select a type.")]
  public int ParadigmId { get; set; }

  public virtual Paradigm Paradigm { get; set; }
}

public class Paradigm
{
    [ScaffoldColumn(false)]
    public int ParadigmId { get; set; }

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

    public List<Entry> Entries { get; set; } 
}

public class EntryViewModel
{
    public Entry Entry { get; set; }
    public IEnumerable<Entry> Entries { get; set; }
}

@model Pylon.Models.EntryViewModel

@{
    ViewBag.Title = "Display";
}

<hr />

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Entry</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Entry.Description)
        </div>
        <div class="editor-field">
            @Html.TextAreaFor(model => model.Entry.Description)
            @Html.ValidationMessageFor(model => model.Entry.Description)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Entry.ParadigmId)
        </div>
        <div class="editor-field">   
            @Html.DropDownListFor(model => model.Entry.ParadigmId, ((IEnumerable<Pylon.Models.Paradigm>)ViewBag.PossibleParadigms).Select(option => new SelectListItem {
                Text = (option == null ? "None" : option.Name), 
                Value = option.ParadigmId.ToString(),
                Selected = (Model != null) && (option.ParadigmId == Model.Entry.ParadigmId)
            }))
            <a href="@Url.Action("Paradigm")"><img src="../../Content/Images/add_icon.gif" /></a> 
            @Html.ValidationMessageFor(model => model.Entry.ParadigmId)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

If I submit the form without entering a description I would like validation to kick in and say "You must include a description." However instead I receive an ArgumentNullException on the DropDownFor line. http://www.wvha.org/temp/ArgumentNullException.png

What should I be doing? As an aside any decent books that cover ASP.NET MVC 3/Razor. I can follow along the basic tuts, but I go astray when I need to deviate to more advance features.

public class EntriesController : Controller
    {
        private readonly PylonContext _context = new PylonContext();

        public ActionResult Display()
        {
            // DropDown
            ViewBag.PossibleParadigms = _context.Paradigms;

            var viewModel = new EntryViewModel {Entries = _context.Entries.ToList()};
            return View(viewModel);
        }

        [HttpPost]
        public ActionResult Display(EntryViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                _context.Entries.Add(viewModel.Entry);
                _context.SaveChanges();
                return RedirectToAction("Display");
            }

            return View(viewModel);
        }
}
2
  • Show us your call to DropDownFor. Chances are, it can't figure out what it's supposed to fill the dropdown list with. Commented Feb 28, 2011 at 22:07
  • Just a tip: instead of posting a screenshot of the exception in visual studio, it is more informative to post the stack trace, which shows exactly where the exception originated. You can get the stack trace from the View detail... link in the exception message. Commented Feb 28, 2011 at 22:17

1 Answer 1

3

It's quite difficult to say without seeing your controller code, but looks like your ViewBag.PossibleParadigms might be null.

Does your insert/update controller action look something like this?

if (ModelState.IsValid) {
    ///...
} else {
    return View(model);
}

If so, you need to put the PossibleParadigms back into the ViewBag (so to speak) before you return back to the view.

If you can post the relevant controller action code, it would be easier to know for sure.

Sign up to request clarification or add additional context in comments.

2 Comments

Super awesome I am really digging the quick responses and accurate fixes from StackOverflow users. Thank you. I added the following code to my [HTTPPost] action in my controller. ViewBag.PossibleParadigms = _context.Paradigms; viewModel.Entries = _context.Entries.ToList();
You're welcome. Voting up helpful answers is a nice way to say thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.