Search code examples
c#asp.net-coredropdownrazor-pages

Dropdown won't send info to db


In one of my previous questions, I asked how I would approach populating a dropdown on my razor page by pulling info from the database. See my question here: Populating dropdown via foreign key

I was advised to do this by adding the following to my PageModel:

public List<Data.Vendor> Vendores { get; set; }

public void OnGet()
{
    List<SelectListItem> test = new List<SelectListItem>();
            //List<Data.File> files = new List<Data.File>();

        Vendores = _context.Vendors.ToList();

        foreach (var item in Vendores)
        {
            test.Add(new SelectListItem { Text = item.VendorName, Value = item.Id.ToString() });
        }
        ViewData["demo"] = test;
}

and on the .cshtml adding the following:

<select asp-for="Files.VendorId" asp-items="@((List<SelectListItem>)ViewData["demo"])"></select>

But when submitting the form in which I want to save the Dropdown selection, when it gets to my Postasync:

[BindProperty]
    public Data.File Files { get; set; }
    public Data.Vendor Vendors { get; set; }

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }
        
        _context.Files.Add(Files);
        await _context.SaveChangesAsync();

        return RedirectToPage("./Index");
    }

The data for that field doesn't get passed through.

If you need to see the full PageModel and .cshtml files I can add them.

I've recorded a video of me going through the process and showing that Vendor Id is null which means nothing is passing through:

https://drive.google.com/file/d/1CxObYQ9czs4OOJYCyr5OMmu-64X9iThz/view?usp=sharing


Solution

  • After I checking the code in Create.cshtml, I find the reason why VendorId can't be bind to the model.

    In your Create.cshtml, you have the code:

    //......
    
    <div class="form-group">
         <label asp-for="Files.VendorId" class="control-label" style="color: white"></label>
         <input asp-for="Files.VendorId" class="form-control" />
         <span asp-validation-for="Files.VendorId" class="text-danger"></span>
    </div>
    
    //......
    
    <select asp-for="Files.VendorId" asp-items="@((List<SelectListItem>)ViewData["demo"])"></select>
    
    //........
    

    Because they all use asp-for="Files.VendorId" to bind value, So they will generate the same name : Files.VendorId in html.

    If there are multiple input attributes with the same name in the form, It will only bind the value of the first input attribute.

    In your video, you don't write any value in VendorId input tag, So VendorId property in Files will not bind any value

    enter image description here

    You can just delete this input attribute and then Files.VendorId will bind the value of dropdown list successfully.