[英]MVC Razor how to get option value from form and set viewmodel property to selected value
填写表单时,用户会提示您从下拉菜单中选择特定选项。 所选的选项应与其余输入一起发送到我的控制器以处理数据。
现在,我对如何发送选定的选项感到困惑。
我要选择选定的站并将其ID发送给我的控制器,以用于创建新工厂。
我想要做的是这样的事情: <input asp-for="stationId" value=@selectedStation.Id">
但是对于我来说,我无法弄清楚如何获得所选的选项电台并设置stationId值发布表单时将模型添加到模型。
<form asp-controller="Plant" asp-action="Create" method="post">
<div class="form-group">
<label for="name">Name:</label>
<input id="name" asp-for="Name" class="form-control" />
<span asp-validation-for="Name"></span>
</div>
<div class="form-group">
<label>Station</label>
<select class="form-control" id="stationId">
@foreach (var station in Model.Stations)
{
<option>@station.Name</option>
}
</select>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
用于表单的视图模型:
public string Name { get; set; }
public string Description { get; set; }
public int StationId { get; set; }
public List<Station> Stations { get; set; }
最后是控制器动作:
[Authorize]
[HttpPost]
public IActionResult Create(CreatePlantViewModel createPlant)
{
var plant = new Plant
{
StationId = createPlant.StationId,
Description = createPlant.Description,
Name = createPlant.Name
};
_context.Add(plant);
_context.SaveChanges();
return RedirectToAction("Index");
}
编辑:在堆栈溢出用户的帮助下,这是需要更改站的select元素的内容:
<div class="form-group">
<label>Station</label>
<select class="form-control" id="stationId" asp-for="StationId">
@foreach (var station in Model.Stations)
{
<option value="@station.Id">@station.Name</option>
}
</select>
</div>
您遇到的问题与没有值发送到控制器这一事实有关。 下列 :
<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
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.