C# MVC Razor如何从窗体获取选项值并将viewmodel属性设置为选定值

C# MVC Razor如何从窗体获取选项值并将viewmodel属性设置为选定值,c#,razor,asp.net-core,.net-core,C#,Razor,Asp.net Core,.net Core,填写表单时,用户会收到一个提示,提示用户从下拉菜单中选择特定选项。所选选项应与其他输入一起发送到我的控制器以处理数据 现在我被困在如何发送所选选项的问题上 我想获取所选站点并将其Id发送给我的控制器,以用于创建新的工厂 我想做的是这样的事情: 您遇到的问题与没有向控制器发送值的事实有关。 以下是: <option>@station.Name</option> @station.Name 应该是: //Assuming that your station class h

填写表单时,用户会收到一个提示,提示用户从下拉菜单中选择特定选项。所选选项应与其他输入一起发送到我的控制器以处理数据

现在我被困在如何发送所选选项的问题上

我想获取所选站点并将其Id发送给我的控制器,以用于创建新的工厂

我想做的是这样的事情:
您遇到的问题与没有向控制器发送值的事实有关。
以下是:

<option>@station.Name</option>
@station.Name
应该是:

//Assuming that your station class has an id
<option value = "@station.id">@station.Name</option> 
//假设您的station类有一个id
@车站,名字
您也可以这样做:

<select id="stationId" asp-for="stationId" asp-items=@(new SelectList(Model.Stations, "stationId", "Name")) class="form-control"></select>

您也可以使用剃须刀,我发现它有助于跟踪您正在做的事情:

@Html.DropDownListFor(m => m.StationId, --Value will be assigned to this variable
                     new SelectList(
                         Model.Stations, 
                         "stationId", 
                         "Name"), --List of values will come from here
                     "-Select Station-", --The default value
                     new {id="stationId",class="Form-control" } -- Attributes you would assignin HTML
    )

非常感谢。但是,仅设置值并没有做到这一点。我还必须在周围的select元素中设置
asp for=“StationId”
。非常感谢你的帮助@Gurkmeja101很高兴这有帮助
<option>@station.Name</option>
//Assuming that your station class has an id
<option value = "@station.id">@station.Name</option> 
<select id="stationId" asp-for="stationId" asp-items=@(new SelectList(Model.Stations, "stationId", "Name")) class="form-control"></select>
@Html.DropDownListFor(m => m.StationId, --Value will be assigned to this variable
                     new SelectList(
                         Model.Stations, 
                         "stationId", 
                         "Name"), --List of values will come from here
                     "-Select Station-", --The default value
                     new {id="stationId",class="Form-control" } -- Attributes you would assignin HTML
    )