I want to make the user only choose between two strings, Internal or Consigned, to be inserted into the InternalConsigned column of a database. How do I do that? This is my current code:
Equipment.cs model class:
public class Equipment
{
[Key]
public int Id { get; set; }
[Required]
[DisplayName("Equipment Name")]
public string Name { get; set; }
[Required]
public int Amount { get; set; }
[Required]
public string Status { get; set; }
[ForeignKey("DepartmentId")]
public int DepartmentId { get; set; }
public Department? Department { get; set; }
[Required]
public string InternalConsigned { get; set; }
public DateTime EOLDate { get; set; }
}
Create action method:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name,Amount,Status,DepartmentId,InternalConsigned,EOLDate")] Equipment equipment)
{
if (ModelState.IsValid)
{
_context.Add(equipment);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["DepartmentId"] = new SelectList(_context.Departments, "Id", "Name", equipment.DepartmentId);
return View(equipment);
}
Create.cshtml:
@model Equipment
@{
ViewData["Title"] = "Create";
}
<h4>Equipment</h4>
<hr />
<div >
<div >
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" ></div>
<div >
<label asp-for="Name" ></label>
<input asp-for="Name" />
<span asp-validation-for="Name" ></span>
</div>
<div >
<label asp-for="Amount" ></label>
<input asp-for="Amount" />
<span asp-validation-for="Amount" ></span>
</div>
<div >
<label asp-for="Status" ></label>
<input asp-for="Status" />
<span asp-validation-for="Status" ></span>
</div>
<div >
<label asp-for="DepartmentId" ></label>
<select asp-for="DepartmentId" class ="form-control" asp-items="ViewBag.DepartmentId"></select>
</div>
<div >
<label asp-for="InternalConsigned" ></label>
<input asp-for="InternalConsigned" />
<span asp-validation-for="InternalConsigned" ></span>
</div>
<div >
<label asp-for="EOLDate" ></label>
<input asp-for="EOLDate" />
<span asp-validation-for="EOLDate" ></span>
</div>
<div >
<input type="submit" value="Create" />
</div>
</form>
</div>
</div>
I know I have to use the select tag in the View, but I'm not sure what to write in the Controller.
CodePudding user response:
If I don't misunderstand your question, You want to write a dropdown list with two options Internal
or Consigned
, So you can refer to this simple demo, Hope it can help you.
List<SelectListItem> test = new List<SelectListItem>();
test.Add(new SelectListItem { Text = "Internal ", Value = "Internal " });
test.Add(new SelectListItem { Text = "Consigned", Value = "Consigned" });
ViewData["demo"] = test;
Then in the view:
<select asp-for="InternalConsigned" asp-items="@ViewBag.demo"></select>
Demo: