asp.Net   发布时间:2022-04-07  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了asp.net-mvc – MVC DropDownList SelectedValue不正确显示大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
@R_221_8450@,没有找到任何解决问题的东西。我在Razor视图中有一个DropDownList,它不会显示在SELEctList中标记为SELEcted的项目。这是填写列表的控制器代码:
var statuses  = new SELEctList(db.orderstatuses,"ID","Name",order.Status.ID.ToString());
ViewBag.Statuses = statuses;
return View(vm);

这是查看代码

<div class="display-label">
   Order Status</div>
<div class="editor-field">
   @Html.DropDownListFor(model => model.StatusID,(SELEctList)ViewBag.Statuses)
   @Html.ValidationmessageFor(model => model.StatusID)
</div>

我走过它,即使在视图中它具有正确的SELEctedValue,但是DDL始终显示列表中的第一个项目,而不管选择的值如何。任何人都可以指出我做错了什么来让DDL默认为SELEctValue?

解决方法

SELEctList构造函数(希望能够传递所选值id)的最后一个参数被忽略,因为DropDownListFor Helper使用您作为第一个参数传递的lambda表达式,并使用特定属性的值。

所以这是丑陋的方法:

模型:

public class Mymodel
{
    public int StatusID { get; set; }
}

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        // TODO: obviously this comes from your DB,// but I hate showing code on SO that people are
        // not able to compile and play with because it has 
        // gazzilion of external dependencies
        var statuses = new SELEctList(
            new[] 
            {
                new { ID = 1,Name = "status 1" },new { ID = 2,Name = "status 2" },new { ID = 3,Name = "status 3" },new { ID = 4,Name = "status 4" },},"Name"
        );
        ViewBag.Statuses = statuses;

        var model = new Mymodel();
        model.StatusID = 3; // preSELEct the element with ID=3 in the list
        return View(model);
    }
}

视图:

@model Mymodel
...    
@Html.DropDownListFor(model => model.StatusID,(SELEctList)ViewBag.Statuses)

这是正确的方式,使用真实的视图模型:

模型

public class Mymodel
{
    public int StatusID { get; set; }
    public IEnumerable<SELEctListItem> Statuses { get; set; }
}

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        // TODO: obviously this comes from your DB,"Name"
        );
        var model = new Mymodel();
        model.Statuses = statuses;
        model.StatusID = 3; // preSELEct the element with ID=3 in the list
        return View(model);
    }
}

视图:

@model Mymodel
...    
@Html.DropDownListFor(model => model.StatusID,Model.Statuses)

大佬总结

以上是大佬教程为你收集整理的asp.net-mvc – MVC DropDownList SelectedValue不正确显示全部内容,希望文章能够帮你解决asp.net-mvc – MVC DropDownList SelectedValue不正确显示所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。