繁体   English   中英

根据其他字段填充字段 ASP.NET Razor 页面

[英]Populate fields based on other fields ASP.NET Razor Pages

我知道这个问题可能已经在这个站点上,但是我的方法中有一些不同的东西,因为我使用了@Html.EditFor 和@Html.DropDownList。 所以我有一个下拉列表,当我在那里选择 ID 时,我想从数据库中检索一些信息,然后在当前表单中填充一些字段。 我知道我应该使用 JS,但我不知道如何使用。

看法:

@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 *@
    }

您可以使用 ajax 从后端获取数据,并将结果数据放在您想要的地方。这是一个简单的演示,从后端获取 selectListItem 并将其放入 div。如果您想做更复杂的事情,您需要分享InsertDto的结构,并清楚地解释您将从 db 中获得什么样的数据,并解释populate some fields in the current form是什么意思? 看法:

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

结果: 在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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