0

I have a model with a foreignkey to another models. From this foreignkey, i want to show into my form a DropDownList with the name of my second models. When i go to create.cshtml or edit.cshtml i have the following error:

ArgumentNullException: Value cannot be null.

Here's my code:

// Models
    public class Timesheet
        {
    public Pharmacy Pharmacy { get; set; }
    }

    // Controllers / ame code on edit.cshtml.cs
    public IActionResult OnGet()
            {
                Dictionary<int, string> pharmacies = new Dictionary<int, string>();
                foreach (Pharmacy p in _context.Pharmacy)
                    pharmacies.Add(p.PharmacyID, p.Name);

                ViewData["PharmacyID"] = pharmacies;
                return Page();
            }

Into create/edit.cshtml, the HTML are:

@Html.DropDownListFor(model => model.ViewData["PharmacyID"], new SelectList(ViewBag.pharmacies , "key", "value"),"-- select --")

I hope you can help me to fix it :)

Thanks per advance !

Yann Btd
  • 409
  • 2
  • 6
  • 18

1 Answers1

0

The problem is you're binding to ViewData using lambda expression instead of model property with value type and using unassigned ViewBag.pharmacies, hence the binding doesn't work as intended.

You should create a model property first:

[BindProperty]
public int PharmacyID { get; set; }

And then bound it to DropDownListFor helper:

@Html.DropDownListFor(model => model.PharmacyID, new SelectList(ViewData["PharmacyID"], "Key", "Value"),"-- select --")

Or use <select> tag helper:

// Page controller (cshtml.cs)
ViewData["PharmacyID"] = new SelectList(pharmacies, "Key", "Value");
<!-- CSHTML view -->
<select asp-for="PharmacyID" asp-items="@ViewData["PharmacyID"]" ...></select>
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
  • What things doesn't work? Are you found any errors? I think you may try create `PharmacyID` property inside a class inheriting `PageModel`, then use the helper to bind with that property. – Tetsuya Yamamoto Jan 28 '19 at 07:03
  • The error are the same of initial: "ArgumentNullException: Value cannot be null." – Yann Btd Jan 28 '19 at 08:20
  • This kind of error usually followed by "parameter name" information, did you checked that? Also try adding viewmodel namespace to `_viewImports` to make sure model binding is enabled. – Tetsuya Yamamoto Jan 28 '19 at 08:33