MVC Dropdownlistfor返回空的选定值

时间:2019-07-11 08:08:40

标签: c# asp.net-mvc razor

this question和其他许多类似,我无法从我的@ Html.Dropdownlistfor中检索选定的值。但是我认为我避免了通常的错误,所以我不确定自己在做什么错。这是我的控制器:

public class AdministrationController : Controller
{
    public ActionResult ParamStatique()
    {
        ParamStatiqueViewModels psvm = new ParamStatiqueViewModels()
        {
            a_NEquipe = "1"
        };

        using (Dal dal = new Dal())
        {
            psvm.EquipesTravaux = dal.GetEquipesTravaux();
        }
        return View(psvm);
    }

    [HttpPost]
    public ActionResult ParamStatique(ParamStatiqueViewModels psvm)
    {

        Debug.WriteLine("NEquipe : " + psvm.a_NEquipe);

        using (Dal dal = new Dal())
        {
            psvm.EquipesTravaux = dal.GetEquipesTravaux();
        }

        return View(psvm);
    }
}

我的ModelView看起来像这样:

public class ParamStatiqueViewModels
{
    public List<EQUIPE_TRAVAUX> EquipesTravaux { get; set; }

    [Display(Name = "N° Équipe")]
    public string a_NEquipe { get; set; }
}

这是我的观点:

@using (Html.BeginForm("ParamStatique", "Administration", null, FormMethod.Post, new { id = "modalform", role = "form" }))
{
    <div class="modal-body" id="modal-body">
        <div class="form-group" id="aNEquipe">
            @Html.LabelFor(m => m.a_NEquipe, new { @class = "col-form-label" })
            @Html.DropDownListFor(m => m.a_NEquipe, new SelectList(Model.EquipesTravaux, "TRAV_SEQ", "TRAV_CODE"), new { @class = "form-control" })
            @Html.ValidationMessageFor(m => m.a_NEquipe, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="modal-footer">
        <button type="submit" class="btn btn-primary">Enregistrer</button>
    </div>
}

所以我的EQUIPE_TRAVAUX类是从EF6生成的:

public partial class EQUIPE_TRAVAUX
{
    public short TRAV_SEQ { get; set; }
    public string TRAV_CODE { get; set; }
}

该下拉列表已正确填充,我可以选择所需的选项,但是当我单击“ Enregistrer”提交按钮时,即使我正确指定了它,它也会在模型中返回空的 a_NEquipe 字段在HTML帮助器中:

@Html.DropDownListFor(m => m.a_NEquipe, new SelectList(Model.EquipesTravaux, "TRAV_SEQ", "TRAV_CODE"), new { @class = "form-control" })

Debug.WriteLine("NEquipe : " + psvm.a_NEquipe);的结果始终为空,如下所示:

  

NEquipe:

如果我将[Required]标签添加到模型中,则客户端验证将阻止表单回发调用。

如何在预期变量a_NEquipe中检索选定的值?

1 个答案:

答案 0 :(得分:1)

尝试像这样指定“文本”和“值”字段:

@Html.DropDownListFor(model => model.a_NEquipe, Model.EquipesTravaux.Select(x => new SelectListItem { Text = x.TRAV_SEQ, Value = x.TRAV_CODE }), new { @class = "form-control"})