Brian Brian - 3 months ago 21
ASP.NET (C#) Question

HTML.DropDownListFor DropDownList

I'm trying to retrieve data from my Database to an HTML instead of retrieving to the Html.DropDownListFor but I'm unable to retrieve to tag.

NewCustomerViewModel

public class NewCustomerViewModel
{
public int CustId { get; set; }

[Required]
public string CustFirstName { get; set; }

[Required]
public string CustLastName { get; set; }

[Required]
public int StId { get; set; }
public IEnumerable<State> States { get; set; }
}


CustomerController

public class CustomerController : Controller
{
private CustomerDbContext _context;

public CustomerController(CustomerDbContext context)
{
_context = context;
}

// GET: /<controller>/
public IActionResult Index()
{
return View(_context.Customers.ToList());
}

public IActionResult Create()
{
var stateNames = _context.States.ToList();
var viewModel = new NewCustomerViewModel
{
States = stateNames
};

return View(viewModel);
}

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Customer customer)
{
if (ModelState.IsValid)
{
_context.Customers.Add(customer);
_context.SaveChanges();
return RedirectToAction("Index");
}

return View(customer);
}
}


Create View

The HTML DropDownListFor below works fine:

@Html.DropDownListFor(m => m.StId, new SelectList(Model.States, "StId", "StName"))


I'm unable to get the select tag to work though.

<select asp-for="StId" asp-items="@Model.States" class="form-control">
<option>Select State</option>
</select>


All of my HTML in my Create view using and rather than the HTML Helpers which is what I'm trying to avoid. I would just like to be able to retrieve the data to the tag instead.

Answer

For the select tag helper, asp-items expects SelectListItem collection\SelectList, and each item in that has a Value and Text property. The Value properties value will be used for the option's value and Text propertiesvalue will be used for the display text of the option in the UI.

Items in your States collection does not have a Value and Text property, but has StId and StName property. So we need to convert this type to SelectListItem type.

So your code should be

<select asp-for="StId"  asp-items="@(new SelectList(Model.States,"StId","StName"))">
     <option>Please select one</option>
</select>

Additional reference

Select Tag Helper in MVC 6