简体   繁体   中英

How To Pass Data From Database Into Chosen Dropdown List Using Javascript in Asp Net Core

I have question about passing data from database into choosen dropdown list.

in the normal Razor page we can use jquery like

$("#DropdownId option:selected").text(obj.DataFromDB);

but in Choosen i cant do that method. and i want the dropdown list have a value, because in the same method in razor Page we only send data into text, and the text not have an id to save again into database.

Here is a working sample which may be helpful, you could refer to:

Model:

 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; }
}

Razor page:

@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");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM