Question

I am a beginner of MVC 4. I wrote code to retrieve data and populate data into dropdownlist which is working fine. But if database is broken, data cannot be retrieved so I want the dropdownlist to display blank or like "no data" in a nice way instead of throw error. I tried to use ViewBag.NoData but it doesnt work. How to solve this problem with my below code:

HomeController C#:

   public ActionResult Index()
    {
        try
        {
            ViewBag.PersonList = Helper.LoadPersonData();

            if (ViewBag.PersonList == null)
            {
                ViewBag.NoPersonData = "NO DATA";
            }
        }
        catch (Exception ex)
        {
            TempData["Message"] = string.Format("An error occurred. Details: {0}", ex.Message);
        }

        return View(persons);
    }

Index.cshtml:

<td>@Html.DropDownList("txtPersonName",((IEnumerable<SelectListItem>)ViewBag.PersonList).Any() ?     new SelectList(ViewBag.PersonList as IEnumerable<SelectListItem>,"Value", "Text",selectedValue:    Session["search"] != null ? (((SearchKey)Session["search"]).PersonName) : (string)ViewBag.NoPersonData ): null, "---------SELECT---------")</td>
Était-ce utile?

La solution

You could just return a list containing an "No Data" entry:

public ActionResult Index()
{
    try
    {
        ViewBag.PersonList = Helper.LoadPersonData();

        if (ViewBag.PersonList == null)
        {
            ViewBag.PersonList = new List<SelectListItem>() 
            { 
                 new SelecListItem()
                 {
                      Value = "nodata", 
                      Text = "No Data" 
                 }
            };
        }
    }
    catch (Exception ex)
    {
        TempData["Message"] = string.Format("An error occurred. Details: {0}", ex.Message);
    }

    return View(persons);
}

Autres conseils

Your PersonList may be empty. Try this:

        if (ViewBag.PersonList == null)
        {
            ViewBag.PersonList = new List<SelectListItem>();
            ViewBag.NoPersonData = "NO DATA";
        }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top