MVC Razor如何从表单获取选项值并将viewmodel属性设置为选定值

时间:2018-12-13 12:10:12

标签: c# razor asp.net-core .net-core

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

现在,我对如何发送选定的选项感到困惑。

我要选择选定的站点并将其ID发送给我的控制器,以用于创建新工厂。

我想要做的是这样的事情: <input asp-for="stationId" value=@selectedStation.Id">,但对我来说,我一生无法弄清楚如何在发布表单时获取选定的选项桩号并将模型的桩号ID设置为其。

<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>

2 个答案:

答案 0 :(得分:1)

您遇到的问题与没有值发送到控制器这一事实有关。 以下:

<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>

答案 1 :(得分:1)

您也可以为此使用剃刀,我发现它有助于跟踪您的工作:

@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
    )