0

I have my CreateGame View with three elements in a row: a label, a dropdownlist and an editbox to put a decimal number.

It goes like this:

<div class="form-group">
    <div class="col-md-1.5">
        @Html.LabelFor(model => model.id1, htmlAttributes: new { @class = "control-label col-md-2" })
    </div>
    <div class="col-md-2">
        @Html.DropDownListFor(model => model.id1, (SelectList)ViewBag.Lista, htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.id1, "", new { @class = "text-danger" })
    </div>
    <div class="col-md-1">
        @Html.EditorFor(model => model.rating_1, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.rating_1, "", new { @class = "text-danger" })
    </div>
</div>

Basically I want to identify which player (from the dropdownlist) played the game and to assign him a certain rating.

Now I have two different scenarios. I can either put an integer number for the rating and everything runs smoothly or I can put a decimal number (that's the point) and a System.InvalidOperationException exception is thrown in this line:

@Html.DropDownListFor(model => model.id1, (SelectList)ViewBag.Lista, htmlAttributes: new { @class = "form-control" })

stating

The ViewData item that has the key 'id1' is of type 'System.Int32' but must be of type 'IEnumerable'.

I know what the error message is saying, but I don't understand how can the rating property changes the way the compiler looks at a line above. How can I be able to insert a decimal number for the rating?

EDIT:

Btw, this is how I create my ViewBag.Lista on my controller:

 var lista = db.Players
      .Select(p => new SelectListItem
      {
          Text = p.name,
          Value = p.ID.ToString()
      }).ToList();

  ViewBag.Lista = new SelectList(lista, "Value", "Text");
paulof91
  • 15
  • 8

1 Answers1

0

Try in your model where you have id1 set:

public IEnumerable<SelectListItem> Your_name_list {get; set;}

And in the view set this list:

@Html.DropDownListFor(model => model.id1, model.Your_name_list, htmlAttributes: new { @class = "form-control" })
Perdido
  • 238
  • 3
  • 12
  • That solved only half my problem, but I'll mark it as the answer as it was usefull for me. I still can't manage to validate decimal numbers for my "rating" property. Is there any validation annotation I'm missing? – paulof91 Apr 10 '16 at 11:22
  • For example in jQuery you can write regexp and you can try validate decimal number for your "rating" property. – Perdido Apr 11 '16 at 09:15
  • 1
    I tried the solution provided by Dave_cz in the topic http://stackoverflow.com/questions/11822480/error-with-decimal-in-mvc3-the-value-is-not-valid-for-field And it's working great so far. – paulof91 Apr 11 '16 at 14:31