发布表单时,我被数据时间输入困住了。
datetime
与型号不匹配,因此 ModelState
无效。我已经对这个问题进行了研究,但找不到任何解决方案。有人可以帮我解决这个问题吗?
这是我的代码 -
Student
模型:
using System.ComponentModel.DataAnnotations;
namespace WebApplication1.Models
{
public class Student
{
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm tt}", ApplyFormatInEditMode = true)]
public DateTime StartDate { get; set; }
}
}
这是视图:
@{
ViewData["Title"] = "Home Page";
}
@model Student
<div class="text-center">
<form method="post" asp-action="Index">
@if (TempData["Error"]!= null)
{
<span>@TempData["Error"]</span>
}
<input type="text" class="form-control" value="14/01/2024 01:04 PM" asp-for="StartDate" asp-format="{0:dd/MM/yyyy HH:mm tt}">
<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>
这是控制器:
[HttpPost]
public IActionResult Index(Student std)
{
if (ModelState.IsValid)
{
TempData["Error"] = std.StartDate.ToString() + " is OK" ;
}
else
{
TempData["Error"] = ModelState.Values.First().Errors.First().ErrorMessage;
}
return View();
}
这是结果:
您似乎在 ASP.NET MVC 应用程序中面临模型绑定问题,特别是日期时间格式。 ASP.NET MVC 中的模型绑定过程会自动将 HTTP 请求数据转换为 CLR 类型,并根据模型验证它们。如果 HTTP 请求中的日期时间格式与模型中的预期格式不匹配,模型绑定将失败,并且
ModelState
将无效。
根据您提供的代码,您的
Student
模型需要特定格式的 StartDate
(dd/MM/yyyy HH:mm tt
)。但是,从视图发送的格式或模型绑定程序如何解释它可能存在问题。
以下是排除故障并可能解决此问题的几个步骤:
检查文化设置: ASP.NET 可能会在与您预期不同的文化环境中解释日期。默认情况下,它使用服务器的区域性设置,这可能与您使用的格式不同 (
dd/MM/yyyy
)。您可以在 Web 应用程序中显式设置区域性以确保一致性。
将以下内容添加到您的
Startup.cs
或全局配置中:
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-GB");
CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("en-GB");
检查 HTTP 请求中的格式化日期: 使用浏览器开发人员工具检查提交时发送的表单数据。确保日期格式符合您的模型的预期。
使用日期时间选择器: 考虑使用日期时间选择器来代替文本输入,以确保用户只能选择正确格式的有效日期。这减少了格式不匹配的可能性。
自定义模型绑定: 如果标准模型绑定未按预期工作,请考虑编写一个可以处理您的特定日期格式的自定义模型绑定器。
服务器端日期解析: 如果由于日期格式问题导致模型状态无效,您可以手动从表单集合中解析日期并将其设置到模型中。
例如:
[HttpPost]
public IActionResult Index(Student std)
{
if (!DateTime.TryParseExact(Request.Form["StartDate"], "dd/MM/yyyy HH:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out var startDate))
{
ModelState.AddModelError("StartDate", "Invalid date format.");
}
if (ModelState.IsValid)
{
std.StartDate = startDate;
TempData["Error"] = std.StartDate.ToString() + " is OK" ;
}
else
{
TempData["Error"] = ModelState.Values.First().Errors.First().ErrorMessage;
}
return View();
}
尝试这些步骤,看看是否能解决您的问题。可能需要根据您的具体应用程序设置和要求进行调整。