Home > Net >  dynamically generated field throwing exception in razor pages
dynamically generated field throwing exception in razor pages

Time:12-10

i have some dynamically generated fields.When i am inserting values into db not able to get values in the list. Its throwing null value exception. Here is my code.

CSHTML.CS FILE

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

OnPost Method

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

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.

EDITED**************

Onget Method

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

Razor View

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

Error Pages

enter image description here

Getting the Billtype values

enter image description here

And My Userrole is Pricing itself. All my dropdown list were working fine before making the changes and i was able to access the page. Please let me know if you need full script.

enter image description here

One more update.When i continue the debug mode the null reference exception is going to next line.

Hi @Rena,

This is my 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;
        }


    }
}

Thanks, Teena

CodePudding user response:

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.

You need change two things to achieve your requirement:

  • Model binding system bind the property by name attribute.

For list model the name should be Model[index].propertyName. In your case, the name should be: RequestFormList[index].propertyName instead of RequestForm.propertyName_index.

  • [BindProperty] only supports for one property, if you want to bind all the properties in your PageModel, you need add [BindProperty] to each property or add [BindProperties] to PageModel:

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

    Or:

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

Besides, your html code uses asp-for="RequestForm.RequestRate_0" but your success function manually add code name="RequestForm.RequestedRate_', their property names are not same.

A whole working demo you could follow:

Model:

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:

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

        <div >
            <label >Requested Rate</label>
            <input type="text" asp-for="RequestFormList[0].RequestRate" disabled="@(Model.UserRole != "Pricing"?true:false)"  />
        </div>
        <div >
            <label >Approval Level</label>
            <input type="text" asp-for="RequestFormList[0].ApprovalLevel" disabled="@(Model.UserRole != "Pricing"?true:false)"  />
        </div>
        <div >
            <label ></label><br />
            <button id="addRow"  disabled="@(Model.UserRole != "Pricing"?true:false)"><i  style="color:white;"></i></button>
        </div>

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

JS in page:

@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" >'
            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" >';
            html  = '<div >';
            html  = '<label  >Bill Type</label >';
            html  = newselect;          
            html  = '</div >';
            html  = '<div >';
            html  = '<label  >Origin</label >';
            html  = '<input type="text" name="RequestFormList['   (rowCount - 1)   '].Origin"  />';
            html  = '</div >';
            html  = '<div >';
            html  = '<label  >Destination</label >';
            html  = '<input type="text"  name="RequestFormList['   (rowCount - 1)   '].Destination"  />';
            html  = '</div >';          
            html  = '<div >';
            html  = '<label  >Requested Rate</label >';
            html  = '<input type="text"name="RequestFormList['   (rowCount - 1)   '].RequestedRate"  />';
            html  = '</div >';
            html  = '<div >';
            html  = '<label  >Approval Level</label >';
            html  = '<input type="text" name="RequestFormList['   (rowCount - 1)   '].ApprovalLevel"  />';
            html  = '</div >';
            html  = '<div >';
            html  = '<label ></label><br />';
            html  = '<button id="removeRow" ><i  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" >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>
}

PageModel:

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()
    {
        //.....
    }

}

Result:

enter image description here

CodePudding user response:

Initialise the RequestFormList as part of its declaration then it will never be null:

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

  • Related