Bojangles
Bojangles

Reputation: 467

Addition of two dropdown boxes in a View

I have the following code and I think by doing so I am overloading a method that already exists with EnteredQuantity. The thing is it almost just works, I guess I am in a little deeper than usual here. When I say almost just works, the text in the drop down is 0,1,2 … 1000 and if I select a “Yard Cut” from the second dropdown, that works fine but the first drop down adds everything with a factor of ten e.g..

If I select “1” from selectList1 and then “1/2 Yard Cut” from selectList2 I get a value of 10.5, not 1.5 and so on.

Now I think I shouldn’t be trying to get it to work this way but the code is not mine, I’m just trying to get it to work to suit my needs. I think ideally it would be nice to have the value of selectList1 + selectList2 be added together from the commented out code in this view and that value become the EnteredQuantity before the update, If you know what I mean.

How can I do that?

Code:

@Html.LabelFor(model => model.EnteredQuantity, new { @class = "qty-label" })<text>:</text> 

var maxQty = 1000;
var selectList1 = new List<SelectListItem>(maxQty + 1);
for (var i = 0; i <= maxQty; i++)
{
    selectList1.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString() });
}
@Html.DropDownListFor(model => model.EnteredQuantity, selectList1, new { @class = "qty-input" })

<text> + </text> 
var selectList2 = new SelectList(new []
{
    new {ID="0",Name="0 Yard Cut"},
    new {ID="0.25",Name="1/4 Yard Cut"},
    new {ID="0.50",Name="1/2 Yard Cut"},
    new {ID="0.75",Name="3/4 Yard Cut"},
}, "ID","Name",0);
ViewData["selectList2"]=selectList2;

//@Html.DropDownList("list",ViewData["selectList2"] as SelectList);

@Html.DropDownListFor(model => model.EnteredQuantity, selectList2, new { @class = "qty-input1" })

Upvotes: 0

Views: 77

Answers (2)

Tallmaris
Tallmaris

Reputation: 7590

UPDATE:

Ignore this and see if you can solve it using @von answer below, which is much better and addresses the same problem.


I don't know what is happening when the form is posted (maybe put some of the code in the question?), but I can guess that it is not "multiplying" by 10, but it is simply concatenating the strings 1 for the first drop-down and 0.50 for the second.

Try and change the second select list removing the zeroes and see what happens:

var selectList2 = new SelectList(new []
{
  new {ID=".0",Name="0 Yard Cut"},
  new {ID=".25",Name="1/4 Yard Cut"},
  new {ID=".50",Name="1/2 Yard Cut"},
  new {ID=".75",Name="3/4 Yard Cut"},
}, "ID","Name",0);

Upvotes: 0

von v.
von v.

Reputation: 17108

I think it's because you are adding the values of the dropdown as text, so you have something like this:

selectList1.val() + selectList2.val()

when it should be like this:

parseFloat(selectList1.val()) + parseFloat(selectList2.val())

Upvotes: 1

Related Questions