Search code examples
javascriptasp.netasp.net-corerazor

Populate fields based on other fields ASP.NET Razor Pages


I know that this question might have been already on this site, but there are some different things in my approach because I use @Html.EditFor and @Html.DropDownList. So I have a drop down list and when I choose the ID there I want to retrieve some information from the DB then populate some fields in the current form. I know that I should use JS but I don't know how.

View:

@model TestApp.Dtos.InsertDto
@using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        <div class="col-md-9">
            @Html.DropDownListFor(model => model.Category, new SelectList(Model.ListOfCategory, "Text", "Text"), "-- Please select --", htmlAttributes: new { @class = "form-control"});
        </div>
        <div class="col-md-9">
            @Html.EditFor(model => model.Car, new{htmlAttributes = new { @class = "form-control" }});
        </div>
@*And then the form continues with other fields and after that the submit button *@
    }

Solution

  • You can use ajax to get data from backend,and put the result data into somewhere you want.Here is a simple demo to get a selectListItem from backend and put it into a div.If you want to do something more complex,you need to share the structure of InsertDto,and explain clearly what kind of data you will get from db and explain what does populate some fields in the current form mean? View:

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        <div class="col-md-9">
            @Html.DropDownListFor(model => model.Category, new SelectList(Model.ListOfCategory, "Text", "Text"), "-- Please select --", htmlAttributes: new { @class = "form-control" ,@onchange = "getData()" })
        </div>
        <div id="dbdata">
        </div>
    }
    

    js:

    <script>
            function getData() {
               $.ajax({
                    type: "POST",
                   data: { Category: $("#Category").val() },
                    url: '/B/GetData',
                }).done(function (result) {
                    $("#dbdata").html("the selected value is " + result.text);
                });
            }
        </script>
    

    Model:

    public class InsertDto
        {
            public string Category { get; set; }
            public List<SelectListItem> ListOfCategory { get; set; }
        }
    

    controller:

    public IActionResult Index(string id)
            {
                InsertDto i = new InsertDto { ListOfCategory = new List<SelectListItem> { new SelectListItem { Text = "t1" }, new SelectListItem { Text = "t2" }, new SelectListItem { Text = "t3" } } };
                return View(i);
            }
            public SelectListItem GetData(string Category) 
            {
                return new SelectListItem { Text = Category, Value = Category + "value" };
            }
    

    result: enter image description here