1

I did check all issues about that but I couldn't figure out how to solve it. I need to your help guys.

Here is my code about dropdownlist. When I post the page I got the error message which I mentioned above. ERROR:

An exception of type 'System.NullReferenceException' occurred in App_Web_ikconokc.dll but was not handled in user code Additional information: Object reference not set to an instance of an object.

I want to use 2 models in 1 view. All works well except @Html.DropDownList. In View:

@model Tuple<Models.Framework.Drink, Models.Framework.Drinks_Category>


    <div class="form-group">
        @Html.LabelFor(tuple => tuple.Item2.Id_category, "Id_category", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("Id_category", new SelectList( Model.Item2.Id_category.ToList()), new { @class = "control-label col-md-2" })

            @Html.ValidationMessageFor(tuple => tuple.Item1.Id_category, "", new { @class = "text-danger" })
        </div>
    </div>

I tried the following code but still get error:

@Html.DropDownList("Id_category", new SelectList( Model.Item2.Id_category, "Value", "Text", Model.Item2), new { @class = "control-label col-md-2" })

Table "Drink" is associated with table "Drinks_Category" with key Id_category. I want to use 2 models in 1 view. Please help me!

  • and what is the error? – Ehsan Sajjad Mar 13 '17 at 13:04
  • oh, sorry, this is : An exception of type 'System.NullReferenceException' occurred in App_Web_ikconokc.dll but was not handled in user code Additional information: Object reference not set to an instance of an object. – Vũ Thành Long Mar 13 '17 at 13:08
  • 1
    why not use viewmodel instead of tuple? – Usman Mar 13 '17 at 13:53
  • Please show us the controller action, wich is retuning that view, and the definition of the Models.Framework.Drinks_Category class. – Miguel Ramirez Mar 13 '17 at 16:49
  • thanks everyone!! @Konstantin Dinev solved the problem for me :) – Vũ Thành Long Mar 13 '17 at 17:52
  • You cannot use a `Tuple` for binding form controls (a `Tuple` has no default constructor, there for cannot be initialized by the `DefaultModelBinder` in the POST method). Use view models. –  Mar 13 '17 at 21:50

1 Answers1

0

I assume that Models.Framework.Drinks_Category is of type IEnumerable. Then what you should bind the DropDownList to is all of the Drinks_Category and pass what the value and text properties are:

@Html.DropDownList(tuple => tuple.Item2.Id_category, 
                   new SelectList( Model.Item2, "Id_category", "TextKey" ),
                   new { @class = "control-label col-md-2" })
Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100