0

currently i'm doing small "Rent a car" application in ASP.NET MVC.

I want to create a page for administrator where he could add cars which he wants to be offered to customers. On this page he could add picture of the car, year of production, type of engine etc. Also, i want to have on this page dropdownlist where he can select if the car has Air Conditioning or not. That dropdownlist would have two options "yes" and "no" so if he for example selects "yes" then i want to populate property "AirConditioning" of my model with that. I stuck on this part and i don't know how to do it.

This is my "Car" model:

public class Car
{
    [Key]
    public int CarID { get; set; }
    public string Model { get; set; }
    [DisplayName("Year of production")]
    public int YearOfProduction { get; set; }
    public string Price { get; set; } 
    public virtual ICollection<FilePath> FilePaths { get; set; }
    public string AlternateText { get; set; }
    public string AirConditioning { get; set; }
}

This is my "Create" (a Car) View:

<h2>Create</h2>

@using (Html.BeginForm("Create", "Cars", FormMethod.Post, new { enctype =  "multipart/form-data" }))
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Car</h4>
    <hr/>
    @Html.ValidationSummary(true, "", new {@class = "text-danger"})
    <div class="form-group">
        @Html.LabelFor(model => model.Model, htmlAttributes: new {@class = "control-label col-md-2"})
        <div class="col-md-10">
            @Html.EditorFor(model => model.Model, new {htmlAttributes = new {@class = "form-control"}})
            @Html.ValidationMessageFor(model => model.Model, "", new {@class = "text-danger"})
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.YearOfProduction, htmlAttributes: new {@class = "control-label col-md-2"})
        <div class="col-md-10">
            @Html.EditorFor(model => model.YearOfProduction, new {htmlAttributes = new {@class = "form-control"}})
            @Html.ValidationMessageFor(model => model.YearOfProduction, "", new {@class = "text-danger"})
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Price, htmlAttributes: new {@class = "control-label col-md-2"})
        <div class="col-md-10">
            @Html.EditorFor(model => model.Price, new {htmlAttributes = new {@class = "form-control"}})
            @Html.ValidationMessageFor(model => model.Price, "", new {@class = "text-danger"})
        </div>
    </div>

    <div class="form-group">
        @Html.Label("Photo", new {@class = "control-label col-md-2"})
        <div class="col-md-10">
            <input type="file" id="Photo" name="upload"/>
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" name="commandName" value="Create"    class="btn btn-default"/>
        </div>
    </div>
</div>   

}

<div>
@Html.ActionLink("Back to List", "Index")
</div>

This is my "Create" Method in "Cars" controller:

[Authorize(Roles = "Administrator")]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include =  "CarID,Model,YearOfProduction,Price")] Car car, HttpPostedFileBase upload)
    {
        if (ModelState.IsValid)
        {
            if (upload != null && upload.ContentLength > 0)
            {
                var photo = new FilePath
                {
                    FileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(upload.FileName), //uniqueness of the file name
                    FileType = FileType.Photo
                };
                car.FilePaths = new List<FilePath>();
                upload.SaveAs(Path.Combine(Server.MapPath("~/Images/Cars"), photo.FileName));
                car.FilePaths.Add(photo);

            }
            db.Cars.Add(car);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(car);
    }

So i would like to know how to implement this dropdownlist in my existing code.

iantukic
  • 87
  • 2
  • 13
  • http://stackoverflow.com/questions/39550804/what-is-the-best-ways-to-bind-html-dropdownlistfor-in-asp-net-mvc5/39550859#39550859 – Shyju Oct 16 '16 at 15:30
  • Why not just a `bool HasAirconditioning` property (and render a checkbox using `@Html.CheckBoxFor(m => m.HasAirconditioning)`)? –  Oct 16 '16 at 23:20

2 Answers2

0

The simplest way is to build a SELECT element with name matching to your entity classes property name.

So simply add this to your view (inside form)

<SELECT name="AirConditioning">
   <option value="Yes">Yes</option>
   <option value="No">No</option>
</SELECT>

Now when you submit the form, the selected option value will be set to the AirConditioning property of your Car class object.

If you do not want to hard code the select options in your view, read further.

You need to pass the list of options for the dropdown to the view.

The below example shows transferring the options to view using ViewBag.

public ActionResult Create()
{
  var options = new List<SelectListItem>{
    new SelectListItem { Value ="Yes", Text="Yes"},
    new SelectListItem { Value ="No", Text="No"}
  };
  ViewBag.AcOptions = options;
  return View();
}

and in your view which is strongly typed to Car class,

@Html.DropDownListFor(x=>x.AirConditioning.ViewBag.AcOptions as List<SelectListItem>)

Another solution is to use strongly typed to view models to pass the dropdown data. This post explains it in detail.

Community
  • 1
  • 1
Shyju
  • 214,206
  • 104
  • 411
  • 497
0

Try to use something like the following to define the dropdownlist in the view:

<div class="form-group">
        @Html.LabelFor(model => model.AirConditioning, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(m => m.AirConditioning, new SelectList(new[] { "Yes", "No" }), htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.AirConditioning, "", new { @class = "text-danger" })
        </div>
    </div>

This will save the selected item to the model.

Faisal
  • 123
  • 1
  • 10