【问题标题】:Setting color in MVC DropDownListFor在 MVC DropDownListFor 中设置颜色
【发布时间】:2017-04-11 17:08:37
【问题描述】:

我正在尝试根据 MVC 中的模型设置下拉颜色。

public class Viewer
{
    public List<SLI> ls { get; set; }

    public string SelectedReport { get; set; }
    //public IEnumerable<SelectListItem> MyReports { get; set; }
    public string PDFLoc { get; set; }
    public List<Status> Stat { get; set; }

}

public class SLI : SelectListItem
{
    public string Color { get; set; }

}

我可以设置“颜色”并将其传递给视图。但我不知道如何创建一个具有样式 color:red 的新 DropDownListFor

我尝试过各种方法,例如:

@Html.DropDownListFor(m => m.SelectedReport, new SelectList(Model.ls, "Value", "Text"), new {style = "color: "+ m=>m.ls.Color +"});

在控制器中:

 public ActionResult Viewer()
    {
        ViewBag.Message = "Your application description page.";

        if (S.UserAuthorized())
        {
            Data D = new Data();


            Viewer V=  new Viewer();
            V.ls = D.GetReportsAssignedToUser();
            V.PDFLoc = "";
            V.SelectedReport = "";
            //Get status of reports
            V.Stat = D.GetReportStatuses(V.ls);


            return View(V);
        }
        return RedirectToAction("Index");
    }

我真的不明白匿名方法。 . .

【问题讨论】:

    标签: asp.net-mvc html.dropdownlistfor


    【解决方案1】:

    你必须像这样创建模型

    public class DDwithColor
        {
    
            public List<SelectListItem> SLI { get; set; }
            public string Color { get; set; }
        }
    

    您的Viewer 模型将是

    public class Viewer
        {
            public DDwithColor ls { get; set; }
            public string SelectedReport { get; set; }
            public string PDFLoc { get; set; }
            public List<Status> Stat { get; set; }
    
        }
    

    Controller

    var viewer = new Viewer();
    var ddwithcolor = new DDwithColor();
    ddwithcolor.Color = "red";
    ddwithcolor.SLI= new List<SelectListItem>() { new SelectListItem() { Text = "test", Value = "1" } };
    viewer.ls = ddwithcolor;
    

    最后在view

    @Html.DropDownListFor(m => m.SelectedReport, new SelectList(Model.ls.SLI, "Value", "Text"), new{ @style=$"color:{Model.ls.Color}"})
    

    【讨论】:

      【解决方案2】:

      修改你的类 -

      public class Viewer
      {
          public List<SLI> ls { get; set; }
      
          public string SelectedReport { get; set; }
          public string PDFLoc { get; set; }
          public List<Status> Stat { get; set; }
          public string DropdownColor { get; set; }
      }
      

      你可以像使用 Jquery -

      $("#SelectedReport option").css("color","@Model.DropdownColor");
      
      • #SelectedReport 是下拉列表的 ID。

      希望这会有所帮助:)

      【讨论】:

        猜你喜欢
        • 2017-03-10
        • 2012-02-24
        • 1970-01-01
        • 1970-01-01
        • 2012-02-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多