DropDownListFor - 需要帮助定义“SelectedValue”属性

时间:2021-01-24 22:54:46

标签: asp.net-mvc html.dropdownlistfor

我需要帮助了解如何在 SelectedValue 中设置 HTML.DropDownListFor 属性。

这是我目前所拥有的: 在模型的另一部分,MA 是存储在数据库中的 int

在模型中:

public IList<SelectListItem> SelectListMA(int MA)
    {
        
        IList < SelectListItem > List = new List<SelectListItem>();
        SelectListItem Item;
        for(int i = 1; i <= 9; i++)
        {
            Item = new SelectListItem
            {
                Value = i.ToString(),
                Text = i.ToString(),
                Selected = i == MA
            };
            List.Add(Item);
        }
        return List;
    }

在控制器中:

ViewBag.MA = _Repository.SelectListMA(5);

最后,在视图中:

@Html.DropDownListFor(model => model.MA, new SelectList(ViewBag.MA, dataValueField: "Value", dataTextField: "Text"))

在视图中,下拉菜单显示正常,但未设置默认值,我使用模型将原始模型传递给 View 进行编辑,因此使用 ViewBag

编辑:需要更多详细信息 - 这是它所属的完整控制器。

    private readonly IRacesRepos _RaceRepository;

    public BaseTeamsController(IRacesRepos _Repository)
    {
        _RaceRepository = _Repository;


    }
    //sets the Model to the repository
    public BaseTeamsController() : this(new ModelRaces()) { }
        

    public ActionResult BEditPlayer(int ID)
        {
    
            Races_Players SelectedPlayer = _RaceRepository.GetPlayerBase(ID);
    
    
            ViewBag.MA = _RaceRepository.SelectListMA(SelectedPlayer.MA);
    
            ViewBag.ST = _RaceRepository.SelectListST(SelectedPlayer.ST);
            ViewBag.AG = _RaceRepository.SelectListAG(SelectedPlayer.AG);
            ViewBag.PA = _RaceRepository.SelectListPA((int)SelectedPlayer.PA);
            ViewBag.AV = _RaceRepository.SelectListAV(SelectedPlayer.AV);
            ViewBag.Race = _RaceRepository.GetRaceBase(SelectedPlayer.RaceID);
            return View(SelectedPlayer);
        }

我使用的是 MVC 版本 5,ModelRaces 是包含代码的模型的名称,MA 是模型中来自数据库的 int。

完整视图

@model BB2020MVC.Models.Races_Players

@{
    ViewBag.Title = "Add Player to " + ViewBag.RaceName;
}



@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
<div class="form-horizontal">
    <h4>Add Player to @ViewBag.RaceName</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.PlayerID)
    @Html.HiddenFor(model => model.RaceID)

    <div class="form-group">
        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10 focus">
            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.MA, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.MA, new SelectList(ViewBag.MA, dataTextField: "Text", dataValueField:"Value") , new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.MA, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.ST, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.ST, new SelectList(ViewBag.ST, dataTextField: "Text", dataValueField: "Value"), new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.ST, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.AG, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.AG, new SelectList(ViewBag.AG, dataTextField: "Text", dataValueField: "Value"), new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.AG, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.PA, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.PA, new SelectList(ViewBag.PA, dataTextField: "Text", dataValueField: "Value") ,new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.PA, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.AV, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.AV, new SelectList(ViewBag.AV, dataTextField: "Text", dataValueField: "Value") ,new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.AV, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Cost, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Cost, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Cost, "", new { @class = "text-danger" })
        </div>
    </div>




    <div class="form-group">
        @Html.LabelFor(model => model.MaxQTY, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.MaxQTY, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.MaxQTY, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

<div>
    @Html.ActionLink("Cancel", "ViewRace", new { ID = Model.RaceID })
</div>

编辑:一直在做一些测试和阅读,问题似乎是视图没有选择 model => model.MA 的选定值,但编辑时该值不为空,因此 SelectListItem 选择的任何值{1}} 或 SelectList 被忽略。 还将任何值传递到 selectedValue 中而不是数字或单词(例如“1”或“Word”,不是 int 或 string 类型的变量)会导致项目不被选中。 没有解决问题,但很有趣。

2 个答案:

答案 0 :(得分:0)

试试这个语法:

在视图中

@Html.DropDownListFor(model => model.MA, ViewBag.MA,"Select One", new { htmlAttributes = new { @class = "form-control" } })

在存储库中:

public SelectList SelectListMA(int MA)
    {
   var List = new List<SelectListItem>();
       
        for(int i = 1; i <= 9; i++)
        {
           List.Add(new SelectListItem
            {
                Value = i.ToString(),
                Text = i.ToString(),
             });
           
        }
     return  new SelectList(list, "Value", "Text",MA);
}

但是您不需要将现有列表转换为 SelectListItem 列表。 只需使用 retun new SelectList(yourlist, "yourvalueproperty", "yourtextproperty",);

答案 1 :(得分:0)

这个问题的答案在于键盘和屏幕之间。

让我解释一下:

在附加测试中,我错误地将 _RaceRepository.GetPlayerBase(ID) 更改为另一个为记录生成新基数的函数。 (即兴突变测试!)

这意味着每次我尝试编辑播放器时,我都会将默认值“1”传递给视图,并在提交时编辑一个从一开始就不存在的模型。

设置正确的函数后,我得到了正确的值,因此所选值的设置自行解决。

不过,我要感谢 Sergey 的查看并尝试提供帮助,并提供了一种更好的方式来提供 SelectList(更好的版本是使用 ViewModel,它必须用于另一部分)。

>

所以对于那些感兴趣的人,这里是解决这个问题的代码:

来自模型:

public SelectList SelectListMA()
    {
        IList<SelectListItem> List = new List<SelectListItem>();
        SelectListItem Item;
        for(int i = 1; i <=9; i++)
        {
            Item = new SelectListItem()
            {
                Value = i.ToString(),
                Text = i.ToString()
            };
            List.Add(Item);
        }
        
        return new SelectList(List,"Value","Text");
    }

来自控制器:

    public ActionResult BEditPlayer(int ID)
    {
        Races_Players SelectedPlayer = _RaceRepository.GetPlayerBase(ID);

        ViewBag.MASelect = _RaceRepository.SelectListMA();
        ViewBag.STSelect = _RaceRepository.SelectListST();
        ViewBag.AGSelect = _RaceRepository.SelectListAG();
        ViewBag.PASelect = _RaceRepository.SelectListPA();
        ViewBag.AVSelect = _RaceRepository.SelectListAV();



        return View(SelectedPlayer);
    }

从视图中: - 因为 SelectList 是为了防止在构建代码时发生错误

@Html.DropDownListFor(model => model.MA, ViewBag.MASelect as SelectList, "Select One") 

此外,对于任何新程序员,根据研究和测试,SelectListSelectListItem 分别有 SelectedValueSelected 用于选择默认值。

SelectedValue 可以是任何标识列表主键或列表新默认值的对象(例如,列表中已有值的整数,或默认值的字符串null).
然而,Selected 是一个布尔值(即 true 或 false),用于选择列表的值。您只需要使用其中一种即可。

请记住 - 如果该值作为 model => model.[Variable] 中的值从控制器传递到视图,则该值将设置为传递的值,而不是 SelectedValue 或 {{ 设置的值1}}。