剃刀页面中动态生成的字段抛出异常

dynamically generated field throwing exception in razor pages

我有一些动态生成的 fields.When 我正在向数据库中插入值,但无法在列表中获取值。它抛出空值异常。这是我的代码。

CSHTML.CS 文件

[BindProperty]
public RequestForm RequestForm { get; set; }
public List<RequestForm> RequestFormList { get;set;}

OnPost 方法

if(RequestFormList.Any())
{
    for(var i=0; i<= RequestFormList.Count(); i++)
    {       
        RequestForm.Counter = i;
        _context.Entry(RequestForm).State = EntityState.Added;
    }
}

当我单击“提交”按钮时,它会转到处理程序,但当它到达 RequestFormList.Any() 时,会抛出错误。理解它没有传递任何值。

已编辑**** **********

Onget 方法

public async Task<PageResult> OnGetAsync(string? RequestID)
        {

            UserRole = HttpContext.Session.GetString("userrole");

            RequestStatus = new SelectList(_context.RequestStatus.OrderBy(e => e.ID), "RequestStatusValues", "RequestStatusValues");
            RequestType = new SelectList(_context.RequestType.OrderBy(e => e.ID), "ReqType", "ReqType");
            Priority = new SelectList(_context.Priority.OrderBy(e => e.ID), "PriorityValues", "PriorityValues");
            
            
            
            Status = new List<SelectListItem> {
                new SelectListItem { Value = "Yes", Text = "Yes" },
                new SelectListItem { Value = "No", Text = "No" }
            };
            
            BillType = GetTypeList();


            RequestFormMaster = await _context.RequestFormMaster.FirstOrDefaultAsync(m => m.RequestID == RequestID);
            
            SLAInformation = await _context.SLAInformation.FirstOrDefaultAsync(m => m.RequestID == RequestID);                
            YTDRevenue = await _context.YTDRevenue.FirstOrDefaultAsync(m => m.RequestID == RequestID);
            ImplementationInfo = await _context.ImplementationInfo.FirstOrDefaultAsync(m => m.RequestID == RequestID);
            ShowRequestChatBox = _context.RequestChatBox.Where(c => c.RequestID == RequestID).OrderBy(c => c.LastModifiedTimeStamp).AsNoTracking().ToList();

            ExistTags = RequestFormMaster.RequestStakeHolders;

            var existtagstring = RequestFormMaster.RequestStakeHolders;
            //after split the existtags, we could get the email list,
            var emaillist = existtagstring.Split(",");
            //we can query the database user table and get the username based on the selected email.
            var existtags = _context.Users.Where(c => emaillist.Contains(c.EmailAddress)).Select(c => new ExistTags()
            {
                Name = c.FirstName + "" + c.LastName, // the full name, firstname + " " + lastname
                Email = c.EmailAddress
            }).ToList();

            var jsonstring = JsonSerializer.Serialize(existtags);
            ViewData["existtag"] = jsonstring;            

            if ((UserRole == "RoleB") && (RequestFormMaster.RequestSubmissionStatus != "Submitted"))
            {
                UserRole = "Submitted"; 
            }
            
            if ((UserRole == "RoleA" || UserRole == "RoleB") && (RequestFormMaster.RequestSubmissionStatus == "Submitted"))
            {
                UserRole = "Implementation";
            }

            return Page();
        }

剃刀视图

            <input type="hidden" id="total" value="1" />
            <div class="col-1">
                <label class="control-label mb-0">Bill Type</label>
                <select id="DrpDwnBillType" asp-for="RequestingList[0].BillType" asp-items="@Model.BillType" class="form-control form-control-sm" disabled="@(Model.UserRole != "RoleB"?true:false)">
                    <option value="">Please Select</option>
                </select>
            </div>
            <div class="col-1">
                <label class="control-label mb-0">Origin</label>
                <input type="text" asp-for="RequestingList[0].Origin" class="form-control form-control-sm" disabled="@(Model.UserRole != "RoleB"?true:false)" />
            </div>
            <div class="col-1">
                <label class="control-label mb-0">Destination</label>
                <input type="text" asp-for="RequestingList[0].Destination" class="form-control form-control-sm" disabled="@(Model.UserRole != "RoleB"?true:false)" />
            </div>
            
            <div class="col-2">
                <label class="control-label mb-0">Requested Rate</label>
                <input type="text" asp-for="LanesRequestingList[0].RequestedRate" class="form-control form-control-sm" disabled="@(Model.UserRole != "RoleB"?true:false)" />
            </div>
            
            <div class="col-2">
                <label class="control-label mb-0">Approval Level</label>
                <input type="text" asp-for="RequestingList[0].ApprovalLevel" class="form-control form-control-sm" disabled="@(Model.UserRole != "RoleB"?true:false)" />
            </div>
            
            <div class="col-1">
                <label class="control-label mb-0"></label><br />
                <button id="addRow" class="btn btn-success" disabled="@(Model.UserRole != "RoleB"?true:false)"><i class="fas fa-plus" style="color:white;"></i></button>
            </div>

错误页面

获取 Billtype 值

我的用户角色是定价本身。 在进行更改之前,我所有的下拉列表都工作正常,并且我能够访问该页面。如果您需要完整脚本,请告诉我。

还有一个 update.When 我继续调试模式,空引用异常将转到下一行。

嗨@Rena,

这是我的Edit.cshtml.cs

namespace SpecialLanePricing.Pages
{
    public class RequestFormEditModel : PageModel
    {
        private readonly IWebHostEnvironment _env;
        private readonly ApplicationDbContext _context;

        public RequestFormEditModel(IWebHostEnvironment env, ApplicationDbContext applicationDbContext)
        {
            _env = env;
            _context = applicationDbContext;
        }

        [BindProperty]
        public RequestFormMaster RequestFormMaster { get; set; }

        [BindProperty]
        public ShipmentProfile ShipmentProfile { get; set; }

        [BindProperty]
        public RatesImplementation RatesImplementation { get; set; }

        [BindProperty]
        public SLAInformation SLAInformation { get; set; }

        [BindProperty]
        public SLPSummary SLPSummary { get; set; }

        [BindProperty]
        public YTDRevenue YTDRevenue { get; set; }

        [BindProperty]
        public ImplementationInfo ImplementationInfo { get; set; }

        [BindProperty]
        public LanesRequestingReduction LanesRequestingReduction { get; set; }

        [BindProperty]
        public List<LanesRequestingReduction> LanesRequestingReductionList { get;set;}

        [BindProperty]
        public RequestChatBox RequestChatBox { get; set; }
        public RequestFormMaster RequestAlreadyExist { get; set; }
        public string RequestID { get; set; }
        public string DisableField { get; set; }
        public string STCCode { get; set; }
        public string PricingAssignee { get; set; }
        public string ReadOnly { get; set; }
        public SelectList RequestStatus { get; set; }
        public SelectList Priority { get; set; }
        public SelectList ActionForSS { get; set; }
        public SelectList BillingCycle { get; set; }
        public SelectList PaymentTerm { get; set; }
        public SelectList RequestType { get; set; }
        public SelectList BillingCurrency { get; set; }
        public SelectList FTBExistingCustomer { get; set; }
        public SelectList FTBLeadSource { get; set; }
        public SelectList Competitors { get; set; }
        public SelectList B2BByB2C { get; set; }
        public SelectList ShipmentPieceType { get; set; }
        public SelectList BaseContractOffer { get; set; }
        public List<SelectListItem> Status { get; set; }
        public SelectList SSExemptions { get; set; }
        public SelectList BillType { get; set; }
        public IList<RequestChatBox> ShowRequestChatBox { get; set; }

        [BindProperty]
        public List<IFormFile> ReqSupportingFiles { get; set; }
        public string ErrorMessage { get; set; }
        public string UserRole { get; set; }
        public string ExistTags { get; set; }
        public string DisabledField { get; set; }
        
        public async Task<PageResult> OnGetAsync(string? RequestID)
        {

            UserRole = HttpContext.Session.GetString("userrole");

            RequestStatus = new SelectList(_context.RequestStatus.OrderBy(e => e.ID), "RequestStatusValues", "RequestStatusValues");
            RequestType = new SelectList(_context.RequestType.OrderBy(e => e.ID), "ReqType", "ReqType");
            Priority = new SelectList(_context.Priority.OrderBy(e => e.ID), "PriorityValues", "PriorityValues");
            ActionForSS = new SelectList(_context.ActionForSalesSupport.OrderBy(e => e.ID), "ActionSS", "ActionSS");
            BillingCycle = new SelectList(_context.BillingCycle.OrderBy(e => e.ID), "BillingCycles", "BillingCycles");
            PaymentTerm = new SelectList(_context.PaymentTerm.OrderBy(e => e.ID), "PaymentTerms", "PaymentTerms");
            BillingCurrency = new SelectList(_context.BillingCurrency.OrderBy(e => e.ID), "BillingCurrencies", "BillingCurrencies");
            FTBExistingCustomer = new SelectList(_context.FTBExistingCustomer.OrderBy(e => e.ID), "FTBOrExist", "FTBOrExist");
            FTBLeadSource = new SelectList(_context.FTBLeadSource.OrderBy(e => e.ID), "FTBLeadSources", "FTBLeadSources");
            Competitors = new SelectList(_context.Competitors.OrderBy(e => e.ID), "Competitor", "Competitor");
            B2BByB2C = new SelectList(_context.B2BbyB2C.OrderBy(e => e.ID), "BtoBBtoC", "BtoBBtoC");
            ShipmentPieceType = new SelectList(_context.ShipmentPieceType.OrderBy(e => e.ID), "ShipmentPieceTypes", "ShipmentPieceTypes");
            BaseContractOffer = new SelectList(_context.BaseContractOffer.OrderBy(e => e.ID), "BaseContractOffers", "BaseContractOffers");
            Status = new List<SelectListItem> {
                new SelectListItem { Value = "Yes", Text = "Yes" },
                new SelectListItem { Value = "No", Text = "No" }
            };
            SSExemptions = new SelectList(_context.SSExemptions.OrderBy(e => e.ID), "SAndSExemptions", "SAndSExemptions");
            BillType = GetTypeList();


            RequestFormMaster = await _context.RequestFormMaster.FirstOrDefaultAsync(m => m.RequestID == RequestID);
            ShipmentProfile = await _context.ShipmentProfile.FirstOrDefaultAsync(m => m.RequestID == RequestID);
            RatesImplementation = await _context.RatesImplementation.FirstOrDefaultAsync(m => m.RequestID == RequestID);
            SLAInformation = await _context.SLAInformation.FirstOrDefaultAsync(m => m.RequestID == RequestID);
            SLPSummary = await _context.SLPSummary.FirstOrDefaultAsync(m => m.RequestID == RequestID);
            YTDRevenue = await _context.YTDRevenue.FirstOrDefaultAsync(m => m.RequestID == RequestID);
            ImplementationInfo = await _context.ImplementationInfo.FirstOrDefaultAsync(m => m.RequestID == RequestID);
            ShowRequestChatBox = _context.RequestChatBox.Where(c => c.RequestID == RequestID).OrderBy(c => c.LastModifiedTimeStamp).AsNoTracking().ToList();

            ExistTags = RequestFormMaster.RequestStakeHolders;

            var existtagstring = RequestFormMaster.RequestStakeHolders;
            //after split the existtags, we could get the email list,
            var emaillist = existtagstring.Split(",");
            //we can query the database user table and get the username based on the selected email.
            var existtags = _context.Users.Where(c => emaillist.Contains(c.EmailAddress)).Select(c => new ExistTags()
            {
                Name = c.FirstName + "" + c.LastName, // the full name, firstname + " " + lastname
                Email = c.EmailAddress
            }).ToList();

            var jsonstring = JsonSerializer.Serialize(existtags);
            ViewData["existtag"] = jsonstring;            

            if ((UserRole == "Sales") && (RequestFormMaster.RequestSubmissionStatus != "Submitted"))
            {
                UserRole = "SalesSubmitted"; 
            }
            
            if ((UserRole == "Sales Support" || UserRole == "Sales") && (RequestFormMaster.RequestSubmissionStatus == "Submitted"))
            {
                UserRole = "RatesImplementation";
            }
            if (UserRole == "Pricing")
            {
                UserRole = "Pricing";
            }

            return Page();
        }

        public async Task<IActionResult> OnPostSubmitChatAsync(RequestChatBox RequestChatBox)
        {
            RequestChatBox.CommentedUser = HttpContext.Session.GetString("firstname") + " " + HttpContext.Session.GetString("lastname");
            RequestChatBox.UserEmail = HttpContext.Session.GetString("emailaddress");
            RequestChatBox.LastModifiedTimeStamp = DateTime.Now;
            RequestChatBox.Comments = RequestChatBox.Comments;
            RequestChatBox.RequestID = RequestChatBox.RequestID;            
            _context.Entry(RequestChatBox).State = EntityState.Added;
            await _context.SaveChangesAsync();
            ShowRequestChatBox = _context.RequestChatBox.Where(c => c.RequestID == RequestChatBox.RequestID).OrderBy(c => c.LastModifiedTimeStamp).AsNoTracking().ToList();
            return new OkResult();

        }

        public async Task<IActionResult> OnPostSubmitAsync()
        {
            RequestStatus = new SelectList(_context.RequestStatus.OrderBy(e => e.ID), "RequestStatusValues", "RequestStatusValues");
            RequestType = new SelectList(_context.RequestType.OrderBy(e => e.ID), "ReqType", "ReqType");
            Priority = new SelectList(_context.Priority.OrderBy(e => e.ID), "PriorityValues", "PriorityValues");
            ActionForSS = new SelectList(_context.ActionForSalesSupport.OrderBy(e => e.ID), "ActionSS", "ActionSS");
            BillingCycle = new SelectList(_context.BillingCycle.OrderBy(e => e.ID), "BillingCycles", "BillingCycles");
            PaymentTerm = new SelectList(_context.PaymentTerm.OrderBy(e => e.ID), "PaymentTerms", "PaymentTerms");
            BillingCurrency = new SelectList(_context.BillingCurrency.OrderBy(e => e.ID), "BillingCurrencies", "BillingCurrencies");
            FTBExistingCustomer = new SelectList(_context.FTBExistingCustomer.OrderBy(e => e.ID), "FTBOrExist", "FTBOrExist");
            FTBLeadSource = new SelectList(_context.FTBLeadSource.OrderBy(e => e.ID), "FTBLeadSources", "FTBLeadSources");
            Competitors = new SelectList(_context.Competitors.OrderBy(e => e.ID), "Competitor", "Competitor");
            B2BByB2C = new SelectList(_context.B2BbyB2C.OrderBy(e => e.ID), "BtoBBtoC", "BtoBBtoC");
            ShipmentPieceType = new SelectList(_context.ShipmentPieceType.OrderBy(e => e.ID), "ShipmentPieceTypes", "ShipmentPieceTypes");
            BaseContractOffer = new SelectList(_context.BaseContractOffer.OrderBy(e => e.ID), "BaseContractOffers", "BaseContractOffers");
            Status = new List<SelectListItem> {
                new SelectListItem { Value = "Yes", Text = "Yes" },
                new SelectListItem { Value = "No", Text = "No" }
            };
            SSExemptions = new SelectList(_context.SSExemptions.OrderBy(e => e.ID), "SAndSExemptions", "SAndSExemptions");
            BillType = new SelectList(_context.BillType.OrderBy(e => e.ID), "BillTypes", "BillTypes");
            
            
            //RequestFormMaster.RequestID = RequestFormMaster.RequestID.Trim();
            //RequestFormMaster.PricingAssignee = RequestFormMaster.PricingAssignee.Trim();
            //RequestFormMaster.PricingAssigneeEmail = RequestFormMaster.PricingAssigneeEmail.Trim();
            //RequestFormMaster.RequestStakeHolders = Request.Form["addedTags"];

            if ((RequestFormMaster.Priority == "Priority “A” – 2 Business Days") || (RequestFormMaster.Priority == "Priority “B” – 4 Business Days"))
            {
                DateTime RequestDeadLine = Convert.ToDateTime(RequestFormMaster.RequestDeadLine);
                RequestFormMaster.RequestDeadLine = RequestDeadLine;
            }
            else
            {
                RequestFormMaster.RequestDeadLine = RequestFormMaster.RequestDeadLine;
            }
            if ((RequestFormMaster.RequestStatus == "") || (RequestFormMaster.RequestStatus == null))
            {
                RequestFormMaster.ProgressBarStatus = "Requestor";
                RequestFormMaster.ProgressBarCounter = 1;
            }
            else if ((RequestFormMaster.RequestStatus == "Pricing Review") || (RequestFormMaster.RequestStatus == "OMS Submission") || (RequestFormMaster.RequestStatus == "KIWI+ Submission") || (RequestFormMaster.RequestStatus == "KAP Analysis"))
            {
                RequestFormMaster.ProgressBarStatus = "Assignee";
                RequestFormMaster.ProgressBarCounter = 2;
            }
            else if ((RequestFormMaster.RequestStatus == "Cross BU Alignment") || (RequestFormMaster.RequestStatus == "OARs Form Alignment"))
            {
                RequestFormMaster.ProgressBarStatus = "Other Functions";
                RequestFormMaster.ProgressBarCounter = 3;
            }
            else if ((RequestFormMaster.RequestStatus == "Analysis Review") || (RequestFormMaster.RequestStatus == "Local TRB Review") || (RequestFormMaster.RequestStatus == "AP-TRB Review"))
            {
                RequestFormMaster.ProgressBarStatus = "Approver";
                RequestFormMaster.ProgressBarCounter = 4;
            }
            else if ((RequestFormMaster.RequestStatus == "Approved by Pricing Executive") || (RequestFormMaster.RequestStatus == "Approved by Pricing Manager") || (RequestFormMaster.RequestStatus == "Approved Local-TRB") || (RequestFormMaster.RequestStatus == "Approved by AP-TRB") || (RequestFormMaster.RequestStatus == "Rejected") || (RequestFormMaster.RequestStatus == "Customer Acceptance & Implementation"))
            {
                RequestFormMaster.ProgressBarStatus = "Completed";
                RequestFormMaster.ProgressBarCounter = 5;
            }
            else if ((RequestFormMaster.RequestStatus == "Implementation Approval (KIWI+)"))
            {
                RequestFormMaster.ProgressBarStatus = "Implemented";
                RequestFormMaster.ProgressBarCounter = 5;
            }

            RequestFormMaster.LastModifiedBy = HttpContext.Session.GetString("firstname") + " " + HttpContext.Session.GetString("lastname");
            _context.Entry(RequestFormMaster).State = EntityState.Modified;

            ShipmentProfile.RequestID = RequestFormMaster.RequestID;
            ShipmentProfile.LastModifiedBy = HttpContext.Session.GetString("firstname") + " " + HttpContext.Session.GetString("lastname");
            ShipmentProfile.LastModifiedTimeStamp = DateTime.Now;
            _context.Entry(ShipmentProfile).State = EntityState.Modified;

            RatesImplementation.RequestID = RequestFormMaster.RequestID;
            RatesImplementation.OpportunityID = RequestFormMaster.OppurtunityID;
            RatesImplementation.CompanyName = RequestFormMaster.CustomerName;
            RatesImplementation.SiteID = RequestFormMaster.SiteID;
            RatesImplementation.AGCMACCode = RequestFormMaster.AGCMACCode;
            RatesImplementation.BillingCycle = RequestFormMaster.BillingCycleName;
            RatesImplementation.PaymentTerms = RequestFormMaster.PaymentTermName;
            RatesImplementation.ExemptionsSS = ShipmentProfile.SSExemptions;
            RatesImplementation.AccountNumbers = RequestFormMaster.AccountsInScope;
            RatesImplementation.LastModifiedTimestamp = DateTime.Now;
            _context.Entry(RatesImplementation).State = EntityState.Modified;

            SLAInformation.RequestID = RequestFormMaster.RequestID;
            SLAInformation.SalesDateOfSubmission = DateTime.Now;
            SLAInformation.LastModifiedTimeStamp = DateTime.Now;
            _context.Entry(SLAInformation).State = EntityState.Modified;

            SLPSummary.RequestID = RequestFormMaster.RequestID;
            SLPSummary.CustomerName = RequestFormMaster.CustomerName;
            SLPSummary.Commodity = ShipmentProfile.Commodity;
            SLPSummary.LastModifiedTimeStamp = DateTime.Now;
            _context.Entry(SLPSummary).State = EntityState.Modified;

            YTDRevenue.RequestID = RequestFormMaster.RequestID;
            YTDRevenue.PricingOwnership = RequestFormMaster.PricingAssignee;
            YTDRevenue.LastModifiedTimeStamp = DateTime.Now;
            _context.Entry(YTDRevenue).State = EntityState.Modified;

            ImplementationInfo.RequestID = RequestFormMaster.RequestID;
            ImplementationInfo.CPAID = RequestFormMaster.CPAID;
            ImplementationInfo.LastModifiedTimeStamp = DateTime.Now;
            _context.Entry(ImplementationInfo).State = EntityState.Modified;

            if (LanesRequestingReductionList.Any())
            {
                for (var i = 0; i <= LanesRequestingReductionList.Count(); i++)
                {
                    LanesRequestingReduction.RequestID = RequestFormMaster.RequestID;
                    LanesRequestingReduction.Counter = i;
                    _context.Entry(LanesRequestingReduction).State = EntityState.Added;
                }
            }

            await _context.SaveChangesAsync();
            TempData["ReqSubmitted"] = "Submitted";
            var foldername = RequestFormMaster.RequestID.ToString();
            var DirectoryPath = Path.Combine(_env.WebRootPath, "Documents", foldername);
            if (!System.IO.Directory.Exists(DirectoryPath))
            {
                System.IO.Directory.CreateDirectory(DirectoryPath);
            }
            if (ReqSupportingFiles != null || ReqSupportingFiles.Count > 0)
            {
                int i = 0;
                foreach (IFormFile upload in ReqSupportingFiles)
                {
                    i++;
                    // Upload file to server folder
                    string ext = Path.GetExtension(upload.FileName).ToLower();
                    if ((ext == ".ppt") || (ext == ".pptx") || (ext == ".xls") || (ext == "xlsx"))
                    {
                        var filesave = Path.Combine(_env.WebRootPath, "Documents", foldername, i + "_" + upload.FileName);
                        using (var stream = System.IO.File.Create(filesave))
                        {
                            await upload.CopyToAsync(stream);
                        }
                    }
                }
            }
            //SendEmailAsync();
            //OnPostUploadFiles(fileData, RequestID);
            return RedirectToPage("/RequestSummary");

            //return Page();
        }

        public JsonResult OnGetSearchValue(string search)
        {
            List<Users> allsearch = new List<Users>();
            if (!string.IsNullOrEmpty(search))
            {
                allsearch = _context.Users.Where(x => x.FirstName.Contains(search) || x.EmailAddress.Equals(search)).ToList();
            }
            return new JsonResult(allsearch);
        }

        public IActionResult OnGetDynamicTypeList()
        {
            return new JsonResult(GetTypeList());
        }

        public SelectList GetTypeList()
        {
            SelectList BillTypeValues = new SelectList(_context.BillType.OrderBy(e => e.ID), "BillTypes", "BillTypes");
            return BillTypeValues;
        }


    }
}

谢谢, 蒂娜

RequestFormList 初始化为声明的一部分,然后它将永远不会为空:

public List<RequestForm> RequestFormList { get;set;} = new List<RequestForm>();

When i click on the Submit button its going to the handler ,but when it reaches RequestFormList.Any(),throwing error. Understood its not passing any value.

你需要改变两件事来达到你的要求:

  • 模型绑定系统通过名称属性绑定 属性。

对于列表模型,名称应为 Model[index].propertyName。在您的情况下,名称应为:RequestFormList[index].propertyName 而不是 RequestForm.propertyName_index.

  • [BindProperty]只支持一个属性,如果要绑定PageModel中的所有属性,需要在每个[=61]中添加[BindProperty] =] 或将 [BindProperties] 添加到 PageModel:

    [BindProperty]
    public RequestForm RequestForm { get; set; }
    [BindProperty]
    public List<RequestForm> RequestFormList { get;set;}
    

    或:

    [BindProperties]
    public class IndexModel : PageModel
    {.....}
    

此外,您的html代码使用asp-for="RequestForm.RequestRate_0" ,但您的成功函数手动添加代码name="RequestForm.RequestedRate_',它们的属性名称不相同.

您可以遵循完整的工作演示:

型号:

public class RequestForm
{
    public string BillType { get; set; }
    public string Origin { get; set; }
    public string Destination { get; set; }
    public string RequestRate { get; set; }
    public string ApprovalLevel { get; set; }
}

页数:

@page
@model IndexModel
<form method="post">
    <div id="newRow" class="form-row mt-2">
        <input type="hidden" id="total" value="1" />
        <div class="col-1">
            <label class="control-label mb-0">Bill Type</label>
            <select id="DrpDwnBillType" asp-for="RequestFormList[0].BillType" asp-items="@Model.BillType" disabled="@(Model.UserRole != "Pricing"?true:false)" class="form-control form-control-sm">
                <option value="">Please Select</option>
            </select>
        </div>
        <div class="col-1">
            <label class="control-label mb-0">Origin</label>
            <input type="text" asp-for="RequestFormList[0].Origin" disabled="@(Model.UserRole != "Pricing"?true:false)" class="form-control form-control-sm" />
        </div>
        <div class="col-1">
            <label class="control-label mb-0">Destination</label>
            <input type="text" asp-for="RequestFormList[0].Destination" disabled="@(Model.UserRole != "Pricing"?true:false)" class="form-control form-control-sm" />
        </div>

        <div class="col-2">
            <label class="control-label mb-0">Requested Rate</label>
            <input type="text" asp-for="RequestFormList[0].RequestRate" disabled="@(Model.UserRole != "Pricing"?true:false)" class="form-control form-control-sm" />
        </div>
        <div class="col-2">
            <label class="control-label mb-0">Approval Level</label>
            <input type="text" asp-for="RequestFormList[0].ApprovalLevel" disabled="@(Model.UserRole != "Pricing"?true:false)" class="form-control form-control-sm" />
        </div>
        <div class="col-1">
            <label class="control-label mb-0"></label><br />
            <button id="addRow" class="btn btn-success" disabled="@(Model.UserRole != "Pricing"?true:false)"><i class="fas fa-plus" style="color:white;"></i></button>
        </div>

    </div>
    <input type="submit" value="Post" />
</form>

页面中的 JS:

@section Scripts
{
<script>
    $("#addRow").click(function () {
    event.preventDefault();
    var rowCount = parseInt($("#total").val());
    rowCount++;
    $("#total").val(rowCount);
    $.ajax({
        type: "Get",
        url: "?handler=DynamicTypeList",    //url depends on yourself...
        success: function (data) {
            //add new select element:
            var newselect = '<select id="DrpDwnBillType" name="RequestFormList[' + (rowCount - 1) + '].BillType" class="form-control form-control-sm">'
            newselect += '<option value="">Please Select</option>';
            $.each(data, function (i, item) {
                newselect += `<option value="${item.value}">${item.text}</option>`;
            });
            newselect += "</select>";
            //generate the new form group
            var html = '';
            html += '<div id="inputRow" class="form-row mt-1">';
            html += '<div class="col-1">';
            html += '<label class="control-label mb-0" >Bill Type</label >';
            html += newselect;          
            html += '</div >';
            html += '<div class="col-1">';
            html += '<label class="control-label mb-0" >Origin</label >';
            html += '<input type="text" name="RequestFormList[' + (rowCount - 1) + '].Origin" class="form-control form-control-sm" />';
            html += '</div >';
            html += '<div class="col-1">';
            html += '<label class="control-label mb-0" >Destination</label >';
            html += '<input type="text"  name="RequestFormList[' + (rowCount - 1) + '].Destination" class="form-control form-control-sm" />';
            html += '</div >';          
            html += '<div class="col-2">';
            html += '<label class="control-label mb-0" >Requested Rate</label >';
            html += '<input type="text"name="RequestFormList[' + (rowCount - 1) + '].RequestedRate" class="form-control form-control-sm" />';
            html += '</div >';
            html += '<div class="col-2">';
            html += '<label class="control-label mb-0" >Approval Level</label >';
            html += '<input type="text" name="RequestFormList[' + (rowCount - 1) + '].ApprovalLevel" class="form-control form-control-sm" />';
            html += '</div >';
            html += '<div class="col-1">';
            html += '<label class="control-label mb-0"></label><br />';
            html += '<button id="removeRow" class="btn btn-danger"><i class="fas fa-trash" style="color:white;"></i></button>';
            html += '</div>';
            //html += '<input type="number" name="[' + (rowCount - 1) + '].Age"  />';
            //add more inputs here...
            //html += '<button id="removeRow" type="button" class="btn btn-danger">Remove</button>';
            html += '</div>';

            $('#newRow').after(html);
        },
        error: function (response) {
            alert(response.responseText);
        }
    });


});
$(document).on('click', '#removeRow', function () {
    var rowCount = parseInt($("#total").val());
    rowCount--;
    $("#total").val(rowCount);
    $(this).closest('#inputRow').remove();
});
</script>
}

页面模型:

public class IndexModel : PageModel
{

    [BindProperty]
    public RequestForm RequestForm { get; set; }
    [BindProperty]
    public List<RequestForm> RequestFormList { get; set; }
    public List<SelectListItem> BillType { get; set; }

    public string UserRole { get; set; } //update code here...
    public IActionResult OnGet()
    {
        BillType = new List<SelectListItem>()
        {
            new SelectListItem(){Text="Bill1",Value="1"},
            new SelectListItem(){Text="Bill2",Value="2"}
        };

        UserRole = "Pricing";   //update code here...
        return Page();
    }
    public IActionResult OnGetDynamicTypeList()
    {
        var data = new List<SelectListItem>()
        {
            new SelectListItem(){Text="aa",Value="1"},
            new SelectListItem(){Text="bb",Value="2"},
            new SelectListItem(){Text="cc",Value="3"}
        };
        return new JsonResult(data);
    }
    public IActionResult OnPost()
    {
        //.....
    }

}

结果: