因此,我对ASP.NET框架还比较陌生,只是try 使用RazorPages.我遇到了模型绑定的问题.它似乎没有像预期的那样工作.

这是我的剃须刀页面.在"OnGet"操作中,我正在动态构建一个表单.对于某些上下文,表单将有大约三种输入,文本输入、日期输入、 Select 和多选输入.QueryField类基本上代表每种输入类型.Name属性表示参数的名称,Required表示该字段是否为必填字段,依此类推.

namespace ReportViewer.Pages
{

    public class QueryField
    {
        public string Name { get; set; }
        public string Label { get; set; }
        public string Type { get; set; }
        public bool Required { get; set; }
        public List<string> Values { get; set; }
        
    }

    public class ReportModel : PageModel
    {

        private readonly AlertService _alertService;
        private readonly ApplicationDbContext _dbContext;

        public Report Report {get; set;}

        [BindProperty]
        public List<QueryField> Fields { get; set; }

        public ReportModel(AlertService alertService, ApplicationDbContext dbContext){
            _alertService = alertService;
            _dbContext = dbContext;
            Fields = new List<QueryField>();
        }
        
        public void OnGet(string reportName)
        {
            var report = _dbContext.Report.FirstOrDefault(r=> r.Name == reportName);

            if (report == null){
                _alertService.AddAlert($"{reportName} is not a valid report. Please check your report name and try again", AlertType.Danger);
            } else {
                Report = report!;
                var parameters = _dbContext.Parameter.Where( p=> p.ReportId == report.Id).ToList();

                foreach (var parameter in parameters){
                    string FieldType;
                    if (parameter.ValidValues.Count() == 0){
                        if (parameter.ParameterType == "Integer"){
                            FieldType = "NumberInput";
                        } else if (parameter.ParameterType == "DateTime"){
                            FieldType = "DateInput";
                        } else {
                            FieldType = "TextInput";
                        }
                    } else {
                        if (parameter.MultiValue){
                            FieldType = "MultiSelectInput";
                        } else {
                            FieldType = "SelectInput";
                        }
                    }
                    
                    QueryField field = new QueryField(){
                        Name = parameter.Name,
                        Label = parameter.Name,
                        Type = FieldType,
                        Required = parameter.Nullable,
                        Values = parameter.ValidValues,
                    };

                    Fields.Add(field);
                }
            }
        }

        public  IActionResult OnPost(List<QueryField> formData)
        {
            if (!ModelState.IsValid){
                return Page();
            }
            Console.WriteLine($"Fields: {formData.Count}");
            return RedirectToPage("Report");
        }

    }
}

在html模板上..

@page "/Reports/{reportName}"
@model ReportViewer.Pages.ReportModel
@{
    ViewData["Title"] = "ReportQuery";
}

@if (Model.Report != null){
    <form data-parsley-validate role="form" id="DUBulkStatementReportForm" method="post">
        <p>
            Please enter/select required detail(s)<br>
            <em><small>Fields marked<span style="color: red">*</span> are required</small></em>
        </p>
        <div class="row">
            <div class="col-md-12">
                <h3>@Model.Report.Name Parameters</h3>
                <hr class="inner-separator" />
            </div>
            <div class="col-md-6">
                <div class="col-md-12">
                    @if (Model.Fields != null)
                    {
                        // --- render form fields here..
                        @foreach (var field in Model.Fields)
                        {
                            <div class="form-group">
                                @if (field.Type == "NumberInput")
                                {
                                    <input class="form-control" type="number" name="@field.Name" />
                                }
                                else if (field.Type == "DateInput")
                                {
                                    @if (field.Required)
                                    {
                                        <p class="required">@field.Label</p>
                                    }
                                    else
                                    {
                                        <p>@field.Label</p>
                                    }
                                    <div class="input-group">
                                        <span class="input-group-addon">
                                            <i class="fa fa-calendar"></i>
                                        </span>
                                        <input type="text" class="form-control dateP" name="@field.Name">
                                    </div>
                                }
                                else if (field.Type == "TextInput")
                                {
                                    @if (field.Required)
                                    {
                                        <label for="@field.Name" class="form-control required">@field.Label</label>
                                        <input type="text" class="form-control" id="@field.Name" required name="@field.Name" />
                                    }
                                    else
                                    {
                                        <label for="@field.Name" class="form-control">@field.Label</label>
                                        <input type="text" class="form-control" id="@field.Name" name="@field.Name" />
                                    }
                                    
                                }
                                else if (field.Type == "MultiSelectInput")
                                {
                                    @if (field.Required)
                                    {
                                        <p class="required">@field.Label</p>
                                        <select class="select2" multiple="multiple" multiple name="@field.Name" required>
                                            @foreach (var value in field.Values)
                                            {
                                                <option value="@value">@value</option>
                                            }
                                        </select>
                                    }
                                    else
                                    {
                                        <p>@field.Label</p>
                                        <select class="select2" multiple="multiple" multiple name="@field.Name">
                                            @foreach (var value in field.Values)
                                            {
                                                <option value="@value">@value</option>
                                            }
                                        </select>
                                    }

                                }
                                else if (field.Type == "SelectInput")
                                {
                                    @if (field.Required)
                                    {
                                        <p class="required">@field.Label</p>
                                        <select name="@field.Name" class="select2" required>
                                            @foreach (var value in field.Values)
                                            {
                                                <option value="@value">@value</option>
                                            }
                                        </select>
                                    }
                                    else
                                    {
                                        <p>@field.Label</p>
                                        <select name="@field.Name" class="select2">
                                            @foreach (var value in field.Values)
                                            {
                                                <option value="@value">@value</option>
                                            }
                                        </select>
                                    }

                                }
                            </div>
                        }
                    }
                </div>
                <div class="col-md-12">
                    <div class="form-group">
                        <button id="PrintPDF" type="button" class="btn btn-info" style="display:inline">
                            <i class="fa fa-file-pdf-o"></i><b>Download PDF</b>
                        </button>
                        <button type="button" id="PrintEXCEL" class="btn btn-success" style="display:inline">
                            <i class="fa fa-file-excel-o"></i><b>Download EXCEL</b>
                        </button>
                    </div>

                    <!--Download PDF Confirmation Modal-->
                    <div class="modal fade" id="DownloadPDFReportModal" data-backdrop="static" data-keyboard="false"
                        tabindex="-1" role="dialog" style="margin: 0 auto;">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                            aria-hidden="true">&times;</span></button>
                                    <h4 class="modal-title"><i class="fa fa-check-square-o success"></i> Download
                                        {{report.name}} Confirmation</h4>
                                </div>
                                <div class="modal-body">
                                    <p><strong>Are you sure you want to continue downloading report?</strong></p>
                                    <p>Click No if you would like to cancel. Click Yes to continue.</p>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-default" data-dismiss="modal">No</button>
                                    <button type="button" class="btn btn-success" data-dismiss="modal"
                                        id="ConfirmDownloadPdf">Yes</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!--End of PDF Confirmation Modal-->

                    <!--Download EXCEL Confirmation Modal-->
                    <div class="modal fade" id="DownloadEXCELReportModal" data-backdrop="static" data-keyboard="false"
                        tabindex="-1" role="dialog" style="margin: 0 auto;">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                            aria-hidden="true">&times;</span></button>
                                    <h4 class="modal-title"><i class="fa fa-check-square-o success"></i> Download
                                        {{report.name}} Confirmation</h4>
                                </div>
                                <div class="modal-body">
                                    <p><strong>Are you sure you want to continue downloading report?</strong></p>
                                    <p>Click No if you would like to cancel. Click Yes to continue.</p>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-default" data-dismiss="modal">No</button>
                                    <button type="button" class="btn btn-success" data-dismiss="modal"
                                        id="ConfirmDownloadExcel">Yes</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!--End of EXCEL Confirmation Modal-->

                    <!--Download Wait Modal-->
                    <div class="modal fade" id="ReportDownloadWaitModal" data-backdrop="static" data-keyboard="false"
                        tabindex="-1" role="dialog" style="margin: 0 auto;">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                            aria-hidden="true">&times;</span></button>
                                    <h4 class="modal-title text-success"><i class="fa fa-check-square-o success"></i>
                                        Downloading File...</h4>
                                </div>
                                <div class="modal-body text-success" id="successMessage">
                                    <p>Please wait while the file is being downloaded...</p>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-default" data-dismiss="modal">Ok</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!--End of Download Wait Modal-->

                </div>
            </div>
        </div>

    </form>

}

表格呈现得很好.我遇到的问题是OnPost动作操纵员的问题.我预计,如果绑定按预期工作,则字段将被填充,但情况似乎并非如此.在本例中,打印formData.Count的结果为0,表示 也许Bundle 不起作用.但是,如果我呼叫Request.Form["field_name"],我可以在请求中看到表单数据.我更喜欢使用绑定方法,而不是解析来自请求对象的数据.

我不知道我错过了什么,或者我是否在以正确的方式做事.任何帮助都很感激.

推荐答案

您需要绑定名称属性,如:name="formData[@i].Name",以便将名称值绑定到OnPost(List formData)(QueryFieldName).

您可以try 删除@foreach (var field in Model.Fields)并添加@for (var i = 0; i< Model.Fields.Count; i++ ),如下所示:

 @if (Model.Fields != null)
  {
      @for (var i = 0; i< Model.Fields.Count; i++ )
 
   {
     // --- render form fields here..
         <div class="form-group">
         @if (Model.Fields[@i].Type == "NumberInput")
             {
             <input class="form-control" type="text" name="formData[@i].Name" />
             }
         else if (Model.Fields[@i].Type == "DateInput")
             {
             @if (Model.Fields[@i].Required)
                 {
                 <p class="required">@Model.Fields[@i].Label</p>
                 }
                 else
                 {
                 <p>@Model.Fields[@i].Label</p>
                 }
                 <div class="input-group">
                     <span class="input-group-addon">
                         <i class="fa fa-calendar"></i>
                     </span>
                     <input type="text" class="form-control dateP" name="formData[@i].Name">
                 </div>
             }
          ...
            

Remember change the field into Model.Fields[@i]. Then we can get the List<QueryField> formData like: enter image description here

Note我们将遇到ModelState.IsValid为False,因为QueryField中的其他属性没有传递给Post方法.

Csharp相关问答推荐

在C#中使用in修饰符

为什么这个Reflection. Emit代码会导致一个DDL ViolationException?

SignalR客户端不会打印队列位置'

Microsoft. VisualBasic. FileIO. FileSystem. MoveFile()对话框有错误?

如何分配对象后的class的属性?

在C#中使用类中的对象值

WeakReference未被垃圾收集

ASP.NET Core AutoMapper:如何解决错误 CS0121调用在以下方法或属性之间不明确

我如何让我的秒表保持运行场景而不重置

我的MRG32k3a算法实现返回的数字超出了预期的[0,1]范围

使用ExtractIconEx(或其他方式)提取最大的可用图标

自定义列表按字符串的部分排序

如何在onNext之前等待订阅者完成?

源代码生成器项目使用`dotnet build`编译,而不是在Visual Studio中编译?

Postgres ENUM类型在第一次运行时对Dapper不可见

未在Windows上运行的Maui项目

正在try 将自定义字体添加到我的控制台应用程序

映射器-如何映射到多个实体

无法向Unity注册Microsoft Logger

C#定时器回调对象上下文?