1

Model

namespace Models
{
    public class PartialTestModel
    {
        public int? NullableProp { get; set; }
    }
}

This works fine

<div class="highlight1">
    @Html.DropDownListFor(m => m.NullableProp, new SelectList(Enumerable.Range(1, 10), Model.NullableProp), "-- Select one --")
</div>

However if a partial view is created for this property

@model System.Int32?

<div class="highlight1">
    Model's value is

    @if (@Model.HasValue)
    {
        @Model.ToString()
    }
    else
    { 
        <text>Null</text>
    }

    @Html.DropDownListFor(m => m, new SelectList(Enumerable.Range(1, 10), Model), "-- Select one --")
</div>

It throws an error

Value cannot be null or empty.
Parameter name: name

[ArgumentException: Value cannot be null or empty.
Parameter name: name]
   System.Web.Mvc.Html.SelectExtensions.SelectInternal(HtmlHelper htmlHelper, String optionLabel, String name, IEnumerable`1 selectList, Boolean allowMultiple, IDictionary`2 htmlAttributes) +396232
   System.Web.Mvc.Html.SelectExtensions.DropDownListFor(HtmlHelper`1 htmlHelper, Expression`1 expression, IEnumerable`1 selectList, String optionLabel, IDictionary`2 htmlAttributes) +35
   System.Web.Mvc.Html.SelectExtensions.DropDownListFor(HtmlHelper`1 htmlHelper, Expression`1 expression, IEnumerable`1 selectList, String optionLabel) +14

The View renders the partial as

@Html.Partial("_PartialTest", Model.NullableProp, new ViewDataDictionary())

new ViewDataDictionary() is added as per the answer in asp.net mvc renderpartial with null model gets passed the wrong type. Without this incorrect model is seen in the partial view when the property value is null. When the property values are not null it can be used

@Html.Partial("_PartialTest", Model.NullableProp)

but still results in the same error as pasted above.

Community
  • 1
  • 1
amit_g
  • 30,880
  • 8
  • 61
  • 118

1 Answers1

1

The problem is that .DropDownListFor(m => m, ... uses the lambda expression to create the input's name. However, m => m doesn't contain a property, so there's no name.

It might work if you instead use m => m.Value, because since this is a lambda expression, it might not actually be executed.

Scott Rippey
  • 15,614
  • 5
  • 70
  • 85