0

In my aplication, always I want to add a new car information to a specific table I must select the car name and if that car was already sold I can select it's owner name. So I have this code for the new row table:

<td>
    @Html.DropDownListFor(model => model.CarName, new SelectList(ViewBag.Cars, "Id", "Description"), new { @class = "iEdit", id = "cars"})
    @Html.ValidationMessageFor(model => model.Description)
</td>
<td data-name="carOwners">
    @Html.DropDownListFor(model => model.Owner, new SelectList(ViewBag.Owners, "Id", "Description"), new { @class = "iDisable", disabled = "disabled" })
    @Html.ValidationMessageFor(model => model.Side)
</td>

But how can I check if the car was sold by the selected value on the first @Html.DropDownListFor and enable the second @Html.DropDownListFor then?

To build my ViewBag.Cars I used this code in my controller:

ICollection<Car> newListCars=new Collection<Car>();

newListCars.Add(new Car(0, "BMW", false));
newListCars.Add(new Car(1, "Toyota", true));

ViewBag.Cars= newListCars;

Car.cs:

public class Car
{
    public int Id { get; set; }
    public string Description { get; set; }
    public bool IsSold { get; set; }

    public Car(int id, string text, bool sold)
    {
        Id = id;
        Description = text;
        IsSold = sold;
    }
}

So basically I want to access the selected ViewBag.Cars.IsSold

Ninita
  • 1,209
  • 2
  • 19
  • 45

1 Answers1

0

Instead of using dropdownlistfor, you could create your own drop down list by doing something like this:

<select name="CarName" class="iEdit" id="cars">
@foreach(Car car in ViewBag.Cars)
{
   <option value="@car.Id" data-issold="@(car.IsSold ? "true" : "false")">@car.Description</option>
}
</select>

Then you can use the data attribute of the selected option like this (jQuery):

   var selected = $('#cars').find('option:selected');
   var isSold = selected.data('issold'); 
Pete
  • 57,112
  • 28
  • 117
  • 166
  • @Ninita, you could always write an extension method which would be a bit cleaner. I quite like the answer by nikeaa in [this post](http://stackoverflow.com/questions/11285303/add-attribute-to-select-list-option#answer-11285916) – Pete Dec 12 '13 at 14:58