MVC 5 dropdown list for selecting an item

user3736648 picture user3736648 · Sep 18, 2014 · Viewed 7.9k times · Source

I am coding an MVC5 internet application, and am getting an error when trying to display a dropdown list for a model attribute that is populated from a ViewModel.

Here is my Create ActionResult:

List<System.Web.Mvc.SelectListItem> blobs = new List<System.Web.Mvc.SelectListItem>();
foreach (var blobItem in blobContainer.ListBlobs())
{
    System.Web.Mvc.SelectListItem selectListItem = new System.Web.Mvc.SelectListItem();
    selectListItem.Value = blobItem.Uri.ToString();
    selectListItem.Text = blobItem.Uri.ToString();
    blobs.Add(selectListItem);
}
AssetViewModel assetViewModel = new AssetViewModel();
assetViewModel.fileNames = blobs;

Here is my Create View code:

<div class="form-group">
    @Html.LabelFor(model => model.asset.webAddress, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(m => m.asset.webAddress, new SelectList(Model.fileNames, "Value", "Text"), "  -----Select List-----  ")
        @Html.ValidationMessageFor(model => model.asset.webAddress)
    </div>
</div>

This is the error that I am getting:

Object reference not set to an instance of an object.

At line:

@Html.DropDownListFor(m => m.asset.webAddress, new SelectList(Model.fileNames, "Value", "Text"), "  -----Select List-----  ")

Can I please have some help with this?

Thanks in advance

EDIT

public class AssetViewModel
{
    public Asset asset { get; set; }
    public List<SelectListItem> fileNames { get; set; }

    public AssetViewModel(Asset asset)
    {
        this.asset = asset;
    }

    public AssetViewModel()
    {

    }
}

Answer

Agaspher picture Agaspher · Sep 18, 2014

Your model asset property m.asset is null. Looks like you want to implement something like this

<div class="form-group">
    @Html.LabelFor(model => model.webAddress, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(m => m.webAddress, new SelectList(Model.fileNames, "Value", "Text"), "  -----Select List-----  ")
        @Html.ValidationMessageFor(model => model.webAddress)
    </div>
</div>