0
votes

I'm a person who has done some simple web programming in the past but now as I return to it and try to create a simple single page app with a form in it that has a "select" in it I'm unable to get beyond a "The name does not exist in the current context" error in my cshtml file. I've selected to do a .NET Core Razor (non-MVC) web app with Visual Studio. Everything I've coded is in two files: Index.cshtml and Index.cshtml.cs and I'm trying to keep it that simple and not implement any Controllers or use lambda syntax - really anything that isn't very plain or dead simple - because my app doesn't need it and I'm trying to limit how much new technology I have to take in to get this simple app done. I think I understand Model Binding because I've gotten it to work for me in these two files when a "select" wasn't being defined. I've been able to bind things like the machineSN you see in the below. I'm trying to bind a List of strings that are in my Index.cshtml.cs file to a "select" statement in my Index.cshtml file.

in Index.cshtml.cs ...

[BindProperties]
public class IndexModel : PageModel
{

public string machineSN = "123456789";
public string machineModel;
public List<SelectListItem> machineModels = new List<SelectListItem>
{
    new SelectListItem {Text="Unknown", Value="0"},
    new SelectListItem {Text="Omega", Value="1"),
}
:
:

in Index.cshtml ...

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}
<div class="text-left">
    <form enctype="multipart/form-data" method="post">
        Machine S/N: <input type="text" name="machineSN" asp-for="machineSN" />
        Model: <select name="machineModel" asp-for="machineModel" asp-items="machineModels"></select>
    </form>
</div>

I get the error message when I hover over the squiggly red line that Visual Studio superimposes under the asp-items string in the cshtml.

I've tried giving other types of things to asp-items - things like a SelectList and an IEnumerable but I still get the error message. I'd prefer to see an answer only involving SelectListItems if that's possible. I've seen posts where people fill the "lists" they give asp-items from databases and OnGet()s but can you show me how to do it in the simple case I've laid out above? Thanks very much for any advice that leads me to a simple solution. I've been wasting a lot of time trying to figure out this error message.

Rich

1

1 Answers

0
votes

It seems that you forgot to put Model.. You can see an example of how to use the select tag helper in the asp.net docs.

So, in your case, you would need to update your select to:

<select asp-for="machineModel" asp-items="Model.machineModels"></select>