I added to my "Todo" class a foreignKey to my "Pharmacy" class. When I add or edit a Todo, no Pharmacy can be linked (from a selectbox). Here's my model:
public class Todo
{
[Key]
public int ID { get; set; }
public Pharmacy Pharmacy { get; set; }
}
public class Pharmacy
{
[Key]
public int PharmacyID { get; set; }
public string Name { get; set; }
public string Pharmacist { get; set; }
[DataType(DataType.PhoneNumber)]
public int Phone { get; set; }
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public int NPA { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string Canton { get; set; }
}
My code's listing to listing all Pharmacies on my Todo:
public class PharmacynamePageModel : PageModel
{
public SelectList PharmacyNameSL { get; set; }
public void PopulatePharmacysDropDownList(ApplicationDbContext _context, object selectedPharmacy = null)
{
var query = (from p in _context.Pharmacy orderby p.Name select p).ToList();
PharmacyNameSL = new SelectList(query, "PharmacyID", "Name", selectedPharmacy);
}
}
Well, at this step, i have this code on my HTML form:
<label asp-for="Todo.Pharmacy" class="control-label"></label>
<select asp-for="Todo.Pharmacy" class="form-control"
asp-items="Model.PharmacyNameSL">
<option value="">-- Select a Pharmacy --</option>
</select>
<span asp-validation-for="Todo.Pharmacy" class="text-danger" />
and my PostAsync() into my create and edit controllers:
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var emptyTask = new Todo();
if (await TryUpdateModelAsync(emptyTask, "Todo",
s => s.ID, s => s.OwnerID,
s => s.Title, s => s.Description,
s => s.DueDate,
s => s.Pharmacy,
s => s.Priority))
{
emptyTask.Status = EnumStatus.Open;
_context.Todo.Add(emptyTask);
await _context.SaveChangesAsync();
if (emptyTask.OwnerID != HttpContext.User.Identity.Name)
{
LogVM.AddLog("Todos", $"{HttpContext.User.Identity.Name} attributed a new task to {emptyTask.OwnerID}.", _context);
}
return RedirectToPage("./Index");
}
PopulatePharmacysDropDownList(_context, emptyTask.Pharmacy);
return RedirectToPage("./Index");
}
All data are mapped/binded, but not the pharmacy field who's the value are always null.
Hope you can help me :).
Thanks per advance.