1

I'm trying to do a dropdownlist from database that have 2 values (zipcode and city). In my table I only have "ZipCode" and "City" meaning I don't have id and I've used my ZipCode as id so far.

I want the dropdown show "Select city"

  • New York 10001
  • New York 10010
  • Los Angeles 90001
  • etc

But now it's only showing like this:

  • New York
  • New York
  • Los Angeles

So if there is two New York then you don't know which one to choose since there is no zipcode. I could change that I shows only zipcodes and not cities and that works, but I want to show both.

In my Customers.cs I have this:

public partial class Customers
{
 public int CustomerId { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string ZipCode { get; set; }
    public virtual Cities Cities { get; set; }
}

In my Cities.cs I have this:

public partial class Cities
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Cities()
    {
        this.Customer = new HashSet<Customers>();
    }

    public string ZipCode { get; set; }
    public string City { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Customers> Customer { get; set; }
}

In my create.cshtml I have this:

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

In controller it's like this:

public ActionResult Create()
{
        ViewBag.ZipCode = new SelectList(db.Cities, "ZipCode", "City");
        return View();
}

How can I change this? I'm stuck..

1 Answer 1

1

Try:

ViewBag.ZipCode = db.Cities.Select(c => new SelectListItem
{
    Value = c.ZipCode,
    Text = $"{c.City} {c.ZipCode}",
});
Sign up to request clarification or add additional context in comments.

1 Comment

Ah awesome thanks!! That worked :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.