0

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()
    {

    }
}
Simon
  • 7,991
  • 21
  • 83
  • 163
  • I suspect The `asset` property of model is null (you dont appear to be initializing it in the code above) –  Sep 18 '14 at 12:39
  • Can you please share Declaration of MODEL on you VIEW? – AK47 Sep 18 '14 at 12:40

2 Answers2

1

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>
Agaspher
  • 485
  • 3
  • 10
0

Your DDLFor syntax looks differently than I have used.

@Html.DropDownListFor(x => x.LeagueId, Model.TeamSL, new { id = "ddlTeam" })

I'm not sure what m.asset.WebAddress is, that could be part of the error as others have stated.

CSharper
  • 5,420
  • 6
  • 28
  • 54