Reputation: 317
Currently I'm populating dropdowns options using an API call. In my model I have something like this:
public List<SelectListItem> getOptions
{
get
{
var options = WebApiHelper.Download<IEnumerable<T>>(
"Controller");
var dropDownOptions = options.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.Value }).ToList();
return dropDownOptions;
}
}
And this is called in a couple of places in the .cshtml (e.g. see below):
@Html.DropDownListFor(m => m.someProperty, Model.getOptions)
List<SelectListItem> GetDropdownOptions()
{
var currentDropdownItems = Model.getOptions;
//some other code to modify dropdown options.
}
Will the Web API only be hit once when I call Model.getOptions? Or will it be called every time since it is inside the get for that property? If it is the latter, what is a good work around for that issue?
Edit: thought about it a little more, would it be better to have these controller populate the values for that property? I have a feeling that an api call gets placed on every call to model.getoptions.
Upvotes: 2
Views: 1408
Reputation:
You WebApiHelper.Download()
will be called each time you access the property and, if you were editing a collection, your current implementation could seriously degrade performance.
While you could define a private field (say) private List<SelectListItem> _Options;
and in the getter, check if its null
and if so, populate it using your WebApiHelper.Download()
method, and then return _Options;
this is still not a preferred implementation since you cannot easily unit test your app.
private List<SelectListItem> _options;
public List<SelectListItem> getOptions
{
get
{
if (_options == null)
{
_options = // call your service
}
return _options;
}
}
Keep your view models as dumb as possible and make your property
public List<SelectListItem> Options { get; set; }
and in the controller, initialize your model and call WebApiHelper.Download()
to populate the collection (and inject WebApiHelper
into your controller)
Upvotes: 2