Eric Herlitz
Eric Herlitz

Reputation: 26297

Add value to dynamically populated list c#

I'm constructing a web page based on ASN.NET MVC3 with Razor templates and Entity. The task is to populate a @Html.DropDownList from the database, so far so good but now I want to insert a static value in the DropDownList.

The code looks as follows

The create method

public ActionResult Create()
{
    var parents = db.Organizations.OrderBy(o => o.Title).ToList();
    var organization = new Organization();
    return View(organization);
} 

Extract from the Razor template

<div class="editor-field">
    @Html.DropDownList("ParentGuid",
    new SelectList(ViewBag.Organizations as System.Collections.IEnumerable,
    "ParentGuid", "Title", Model.ParentGuid))
</div>

So, the above code works but Im stuck in figuring out how to insert an empty row in the dropdown.

Upvotes: 1

Views: 1763

Answers (5)

Eric Herlitz
Eric Herlitz

Reputation: 26297

I ended up using

<div class="editor-field">
    @Html.DropDownListFor(model => model.ParentGuid,
    new SelectList(ViewBag.Organizations as System.Collections.IEnumerable,
    "OrganizationGuid", "Title", Model.ParentGuid), "")
</div>

The method serving the template looks like this

public ActionResult Create()
{
    try
    {
        ViewBag.Organizations = db.Organizations.OrderBy(o => o.Title).ToList();

        var organization = new Organization();
        return View(organization);
    }
    catch (Exception e)
    {
        ViewData["error"] = string.Concat(e.Message, " ", e.StackTrace);
        return RedirectToAction("Index");
    }
} 

Upvotes: 0

Waqas Raja
Waqas Raja

Reputation: 10870

I am not much familiarize with @ however, if you tried the overload?

@Html.DropDownList("ParentGuid",
    new SelectList(ViewBag.Organizations as System.Collections.IEnumerable,
    "ParentGuid", "Title", Model.ParentGuid), "Your empty option text here")

Upvotes: 3

cwharris
cwharris

Reputation: 18125

You could add a row with an empty string to your model before passing it to the view, no?

Upvotes: 1

brandon
brandon

Reputation: 1230

In your controller Create(), just add an empty string to the head of the "parents" list.

Upvotes: 0

joe_coolish
joe_coolish

Reputation: 7259

You could recreate the array previous to adding it to the list. Something like this:

List<SelectListItem> itms = new List<SelectListItem>();

var blank = new SelectListItem();
blank.Selected = true;
itms.Add(blank);

foreach (var stat in model)
{
    var s = new SelectListItem();
    s.Text = stat.Text;
    s.Value = stat.FeedBackTypeID + "";

    itms.Add(s);
}

and then use that

Upvotes: 0

Related Questions