I'm pretty new to web programming in general and am trying to make a simple data entry page using Razor Pages on ASP.Net Core 3.0.
I'm having some trouble with the SelectList in the tag. The behavior I'm trying to get is capturing the ID value from a SelectList within the view, which is simply refusing to work correctly, at least on the OnPost method.
Here's my code:
Get the records I need using FromSqlRaw
Main table and List of items as IEnumerable
Code in the View as SelectList
How the list looks on the actual site
What I really need is to capture the ID value (IDCON) of the list item and post it to the bound property in the asp-for, but for whatever reason the value returned is always null. Any ideas on what I'm doing wrong or perhaps a different approach?
Any help would be greatly appreciated.
You can try to add [BindProperty]
,Here is a working demo with fake data.
cshtml:
<form method="post">
<label asp-for="registro.IDCON">Consecuencia</label>
<select asp-for="registro.IDCON" asp-items="@(new SelectList(Model.consecuencias,"IDCON","DSCCON"))">
<option value="">---Elegir Consecuencia---</option>
</select>
<span asp-validation-for="registro.IDCON" class="text-danger"></span>
<input type="submit" value="submit"/>
</form>
cshtml.cs:
public class TestIDCONModel : PageModel
{
[BindProperty]
public ROCONSEC registro { get; set; }
[BindProperty]
public List<ROCONSEC> consecuencias { get; set; }
public IActionResult OnGet()
{
consecuencias = new List<ROCONSEC> { new ROCONSEC { IDCON = 1, DSCCON = "PROCESO RALENTIZADO" }, new ROCONSEC { IDCON = 2, DSCCON = "PROCESO DESTRUIDO" } };
return Page();
}
public IActionResult OnPost()
{
int IDCON = registro.IDCON;
return Page();
}
}