Вот рабочий пример, который может быть полезен, вы можете обратиться к:
Модель:
public class Project
{
public int Id { get; set; }
[Required]
public string ProjectName { get; set; }
[Required]
public int Clientid { get; set; }
public Client Client { get; set; }
}
public class Client
{
[Key]
public int id { get; set; }
[Required]
public string ClientName { get; set; }
public string NewName { get; set; }
}
Страница бритвы:
@page
@model RazorPages2_2Test.Pages.Projects.CreateModel
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Project.ProjectName" class="control-label"></label>
<input asp-for="Project.ProjectName" class="form-control" />
<span asp-validation-for="Project.ProjectName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Project.Client" class="control-label"></label>
<select asp-for="Project.Clientid" asp-items="Model.ClientList" class="form-control clientselectlist">
<option value="">-- Select Client --</option>
</select>
<span asp-validation-for="Project.Clientid" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(".clientselectlist").change(function () {
var id = $(".clientselectlist option:selected").val();
$.ajax({
type: "get",
url: "/Projects/Create?handler=DataFromDb&clientId="+id,
success: function (result) {
$(".clientselectlist option:selected").text(result.newName);
}
})
});
</script>
}
PageModel
public class CreateModel : PageModel
{
private readonly RazorPages2_2Test.Data.RazorPagesDbContext _context;
public CreateModel(RazorPages2_2Test.Data.RazorPagesDbContext context)
{
_context = context;
}
public IActionResult OnGet()
{
var Clients = from c in _context.Clients
orderby c.ClientName
select c;
ClientList = Clients.Select(x => new SelectListItem
{
Text = x.ClientName,
Value = x.id.ToString()
}).ToList();
return Page();
}
[BindProperty]
public Project Project { get; set; }
[BindProperty]
public List<SelectListItem> ClientList { get; set; }
public async Task<IActionResult> OnGetDataFromDb(int clientId)
{
var client =await _context.Clients.FindAsync(clientId);
return new JsonResult(client);
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
_context.Project.Add(Project);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
}