【问题标题】:Unable to Set DropDownlist with pre-selected value无法使用预选值设置 DropDownlist
【发布时间】:2017-05-08 03:46:52
【问题描述】:

无法使用预选值填充 dropdonwlist。使用预选值填充适用于 viewbag 方法。但是,当我尝试使用基于模型的方法时,我发现没有运气。

public ActionResult Edit(int?id)
{
    Job_ClientVM Vm = new Job_ClientVM();
    Vm.Job_Info = Get_jobdetails(id);
    //4 is desired pre-selected ID value     
    Vm.Recruiters = new SelectList(db.Recruiter_Info.ToList(), "Id", 
    "Recruiter_Name",4);
}

这是我的观点

@Html.DropDownListFor(Model => Model.SelectedRecruiterID, Model.Recruiters, "Assign Recruiter", new { @class = "form-control" })

【问题讨论】:

    标签: asp.net linq-to-sql asp.net-mvc-5 razorengine


    【解决方案1】:

    在将模型传递给视图之前,您需要在 GET 方法中设置 SelectedRecruiterID 的值。

    public ActionResult Edit(int?id)
    {
        Job_ClientVM Vm = new Job_ClientVM();
        Vm.Job_Info = Get_jobdetails(id);    
        Vm.Recruiters = new SelectList(db.Recruiter_Info.ToList(), "Id", "Recruiter_Name");
        // Set the value of SelectedRecruiterID
        Vm.SelectedRecruiterID = 4;
        // Pass the model to the view
        return View(Vm);
    }
    

    请注意,在 SelectList 构造函数中设置 Selected 属性(第 4 个参数)是没有意义的 - 在绑定到模型属性时它会被忽略(在内部,该方法构建一个新的 IEnumerable<SelectListItem> 并根据财产的价值。

    【讨论】:

    • 您的解决方案正在运行,但是当我尝试分配 Vm.SelectedRecruiterID=Vm.Job_Info.Recruiter_ID;我面临错误无法转换 int 类型?到 int 类型转换丢失。关于如何继续的任何想法
    • 我不知道您的模型是什么或SelectedRecruiterIDJob_Info.Recruiter_ID 是什么类型,但显然它们是不同的。没有看到你的模型的最佳猜测是Vm.SelectedRecruiterID = Vm.Job_Info.Recruiter_ID.GetValueOrDefault();
    • 我通过将 SelectedRecruiterID 更改为“public Nullable SelectedRecruiterID { get; set; }”解决了这个问题。谢谢
    • 因为它是一个视图模型,它应该可以为空(请参阅this answer 以获得解释)。你在做什么 - 创建一个视图模型并包含 SelectList 的属性并使用强类型 DropDownListFor() 方法是最佳实践:)。如果您需要返回视图,请记住在 POST 方法中重新填充 Recruiters 属性,因为 ModelState 无效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-18
    • 2010-11-28
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    • 2010-09-22
    相关资源
    最近更新 更多