2

Currently my code looks like this:

@Html.DropDownListFor( m => m.regionIdentification, new SelectList(Model.UI.region, 
    "Value", "Text", Model.region), new {@class = "form-control input-sm"})

I'm looking for a simple was to ignore nulls in the list when I populate the DropDown.

For example:

.notNull()

I'm trying to avoid having to use linq or update stored procedures. Any suggestion would be helpful, thanks!

5
  • 2
    m.regionIdentification.Where(r=> r != null) But you don't want to use LINQ. Commented Sep 17, 2014 at 19:11
  • 1
    I'm trying to avoid having to use linq why? Commented Sep 17, 2014 at 19:12
  • @Habib, Actually, shouldn't it be new SelectList(Model.UI.region.Where(r -> r != null)...? Commented Sep 17, 2014 at 19:13
  • @Habib Thanks, I didn't realize that was still linq. I was trying to avoid a direct db query. I'm new Commented Sep 17, 2014 at 19:15
  • 1
    @jshoop - Linq allows you to work with any object list. Entity Framework is the tool that allows you to leverage linq when you interact with a database. Commented Sep 17, 2014 at 19:40

1 Answer 1

2

I think you have several options:

  1. Extend SelectList class to add the ability to filter out the values that are not valid in the constructor, and then use your custom class instead of SelectList.
  2. Use a Razor inline function to filter the values that are null, since you don't prefer LINQ. See this link for a sample inline function syntax: http://weblogs.asp.net/hajan/functions-inside-page-using-razor-view-engine-asp-net-mvc
  3. Do some more validation in the Controller or Model class when you are populating the list of regions to prevent adding invalid values in the collection.
  4. Create your own collection that does not allow Null values, or extend one of the existing collections, so you make sure your collection contains only valid values. Read this for ideas: Are there any collections in .NET that prevent null entries?
  5. Use a LINQ extension method in Razor like .Where(r=> r != null)

I would still recommend using LINQ (no. 5 in my list), since it's the simplest and safest approach.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.