【问题标题】:ASP.NET MVC Select Drop Down list, set the default value and retrieve the selected valueASP.NET MVC 选择下拉列表,设置默认值并检索所选值
【发布时间】:2022-01-17 03:56:18
【问题描述】:

我相信答案很简单。我有一个带有值列表的<select>。对于编辑模式,我希望下拉菜单显示当前值并在视图呈现时选择。并且当表单提交时,获取一个可能的新选择值并将其传递回控制器。任何帮助将不胜感激。

从外观上看:

<td style="padding:15px">
    <label asp-for="OrganizationTypeId" class="form-control-label" style="font-weight:bold">Organization</label>
    <select asp-for="OrganizationTypeId" class="form-control" style="width:450px" asp-items="@(new SelectList(Model.orgTypes, "Id", "OrganizationName"))">
        <option value="" disabled hidden selected>Select Organization....</option>
    </select>
</td>

控制器中的代码:

dr = _electedOfficials.getDeputyReg(jurisdictionId, Id);

dr.orgTypes = _electedOfficials.GetOrganizationTypes(jurisdictionId);

return View(dr);

组织类型类

    public int Id { get; set; }
    public string OrganizationName { get; set; }

【问题讨论】:

    标签: asp.net-mvc select


    【解决方案1】:

    其中一种解决方案是准备SelectListItem 的列表并将选定的项目Id 返回给控制器:

    public ActionResult Index()
    {
        // ...
        dr.orgTypes = _electedOfficials.GetOrganizationTypes(jurisdictionId);
    
        var model = dr.orgTypes.Select(d => new SelectListItem() { Selected = (d.Id == /* id of default selection*/), Text = d.OrganizationName, Value = d.Id.ToString() }).ToList(); 
    
        return View(model);
    }
    
    [HttpPost]
    public ActionResult Index(int? seletedId)
    {
        if (ModelState.IsValid && seletedId.HasValue)
        {
            // Processing the selected value...
        }           
        return RedirectToAction("Index");           
    }
    

    在视图中:

    @model IEnumerable<SelectListItem>
    
    <script type="text/javascript">
    
        $(document).ready(function () {
            var e = document.getElementById("OrgTypesList");
            $("#SeletedId").val(e.options[e.selectedIndex].value);
        });
    
        function changefunc(val) {
            $("#SeletedId").val($("#OrgTypesList").val());
        }
    </script>
    
    @using (Html.BeginForm("Index", "Home"))
    {
        @* To pass `SeletedId` to controller *@
        <input id="SeletedId" name="SeletedId" type="hidden" />
    
        <label asp-for="OrganizationTypeId" class="form-control-label" style="font-weight:bold">Organization</label>
        @Html.DropDownList("OrgTypesList", Model, "Select Organization...", new { @class = "form-control", @onchange = "changefunc(this.value)" })
    
        <button type="submit" class="btn btn-primary">Save</button>
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      相关资源
      最近更新 更多