asp.net mvC语言 传递空字符串当用户不输入任何在@HtmlTextboxFor



面对一个问题,我有一个@HtmlTextboxFor当用户不插入任何东西,它返回的错误如何传递空字符串或null,如果它留下空白。

parameters字典包含一个空的parameter条目非空类型的FromDate。DateTime '

当用户没有插入任何内容时,传递一个空字符串或null作为值,否则传递user插入的值。

我的代码有什么问题

public class ReportViewModel
    {
        public string FromDate { get; set; }
        public string ToDate { get; set; }
    private tDbContext tDbContext;
    private IReportService reportService;
    public void ViewReportList(DateTime fromDate, DateTime toDate)
    {
        reportService = new ReportService(tDbContext);
        ReportList = reportService.GetReportsList(fromDate, toDate);
    }
    }
视图

@model Req.ViewModels.ReportViewModel
@using (Html.BeginForm("Index", "Print", FormMethod.Post))
{
 @Html.TextBoxFor(m => m.FromDate, new { @readonly = "readonly", @class = "date-picker form-control"})
@Html.TextBoxFor(m => m.ToDate, new { @readonly = true, @class = "date-picker form-control"})
}

Index操作

[HttpPost]
        public ActionResult Index(ReportViewModel reportViewModel,DateTime FromDate, DateTime ToDate)
        {
...
reportViewModel.ViewReportList(FromDate, ToDate);
                return View("Index", reportViewModel);
            }

建议后修改代码

[HttpPost]
            public ActionResult Index(ReportViewModel reportViewModel)
            {
    ...
    reportViewModel.ViewReportList(reportViewModel.FromDate, reportViewModel.ToDate);
                    return View("Index", reportViewModel);
                }

视图模型

public class ReportViewModel
        {
            public DateTime? FromDate { get; set; }
        public DateTime? ToDate { get; set; }
        private tDbContext tDbContext;
        private IReportService reportService;
        public void ViewReportList(DateTime fromDate, DateTime toDate)
        {
            reportService = new ReportService(tDbContext);
            ReportList = reportService.GetReportsList(fromDate, toDate);
        }
        }

现在我得到了这个错误它显示了错误

是匹配的最佳重载方法ViewReportList (System.DateTime System.DateTime)

更改后

您的VM中的字符串字段FromDate将被初始化为空字符串,无论如何似乎不是问题。这里的问题是您的POST方法。模型绑定器试图将FromDate字符串转换为参数的日期时间,根据方法签名,它不是可选的。

如果这些参数应该是可选的,您应该通过使日期参数为空来指定:

public ActionResult Index(ReportViewModel reportViewModel, DateTime? FromDate, DateTime? ToDate)

或提供默认值:

public ActionResult Index(ReportViewModel reportViewModel, DateTime FromDate = DateTime.MinValue, DateTime ToDate = DateTime.MaxValue)

但是,视图模型中已经有日期了,所以这些参数是多余的。

我的建议:

[HttpPost]
public ActionResult Index(ReportViewModel reportViewModel)
{
    ...
    reportViewModel.ViewReportList(reportViewModel.FromDate, reportViewModel.ToDate);
    return View("Index", reportViewModel);
}

并将虚拟机本身更改为DateTimes:

public class ReportViewModel
{
    public DateTime FromDate { get; set; }  // maybe make these nullable or set defaults?
    public DateTime ToDate { get; set; }
    ...
}

尝试使用默认值

@Html。TextBoxFor(m => m. fromdate, new {@readonly =" readonly", @class =" date-picker form-control",Value="})

相关内容

最新更新