如果ViewBag为null或为空,如何隐藏@ Html.DropDownList

时间:2017-04-05 17:19:20

标签: c# html asp.net asp.net-mvc-4

我有@ Html.DropDownList,它在编辑模式下从控制器获取数据。如果list为null或为空,我需要隐藏DropDown元素并显示一些消息。

我在视图中尝试使用此代码,但一直给我结果,并显示空下拉列表:

 @if(ViewBag.DatumRID != null)
                {
                    <div class="col-md-10">
                        @Html.DropDownList("DatumRID", null, htmlAttributes: new { @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.DatumRID, "", new { @class = "text-danger" })
                    </div>
                }
                else
                {
                    <h6 style="color:#ff0000"> NO RECORDS.</h6>
                }

来自控制器的代码在这里:

ViewBag.DatumRID = new SelectList(db.tbl_relacii.Where(x => x.DatumR == tbl_rezervacii.DatumP).OrderBy(x => x.DatumR), "relID", "DatumForDisplay", tbl_rezervacii.DatumRID);

当记录fount下拉列表正常时,但当记录为空时,下拉列表显示为空。

2 个答案:

答案 0 :(得分:0)

也检查清单大小。为了正确显示数据,SelectList必须包含多于零的项目。试试这个:

@if(ViewBag.DatumRID != null && ViewBag.DatumRID.Count > 0)
{
      <div class="col-md-10">
          @Html.DropDownList("DatumRID", null, htmlAttributes: new { @class = "form-control" })
          @Html.ValidationMessageFor(model => model.DatumRID, "", new { @class = "text-danger" })
      </div>
}
else
{
      <h6 style="color:#ff0000"> NO RECORDS.</h6>
}

更新: 您可以尝试更新您的控制器代码:

    List<SelectListItem> viewList = new List<SelectListItem>();
    viewList.AddRange(new SelectList(db.tbl_relacii.Where(x => x.DatumR == tbl_rezervacii.DatumP).OrderBy(x => x.DatumR), "relID", "DatumForDisplay", tbl_rezervacii.DatumRID));
    ViewBag.DatumRID = viewList;

传递&#34; viewList&#34;在razor标记处反对DropDownList帮助器。

答案 1 :(得分:0)

好的。我四处搜寻,可以找到任何合理的方法。选择列表没有像大多数列表一样具有Count()或any()方法。这是我想出的:

   public static void Main(string[] args)
   {
        // NLog: setup the logger first to catch all errors
        var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
        try
        {
            logger.Debug("init main");
            BuildWebHost(args).Build().Run();
        }
        catch (Exception ex)
        {
            //NLog: catch setup errors
            logger.Error(ex, "Stopped program because of exception");
            throw;
        }
        finally
        {
            // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
            NLog.LogManager.Shutdown();
        }
    }

    public static IWebHostBuilder BuildWebHost(string[] args)
    {
            var webHost = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    var env = hostingContext.HostingEnvironment;
                    config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                          .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
                    config.AddEnvironmentVariables();
                })
                .UseStartup<Startup>()
                .ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
                })
                .UseNLog();
        return webHost;
    };