【发布时间】:2020-06-06 00:31:27
【问题描述】:
我有一个 Asp.Net MVC5 项目,当在 ViewModel 上使用 requires 属性时,如果 ViewModel 无效,我无法访问我的控制器。但是,它只发生在特定的屏幕上。
我需要这样,即使使用错误的 VM,此请求也会到达我的控制器,以便在我的视图中执行另一个操作(在这种情况下,一个微调器被隐藏)。
我的代码示例:
视图模型:
public class ParameterizationViewModel
{
/// <summary>
/// Name of Parameterization.
/// </summary>
[Required(ErrorMessageResourceName = "LabelErrorFieldRequired", ErrorMessageResourceType = typeof(ResourcesGSC.Language))]
[Display(Name = "LabelName", ResourceType = typeof(ResourcesGSC.Language))]
public string Name { get; set; }
}
控制器:
public class ParameterizationController : BaseController
{
[HttpGet]
public ActionResult Index(string id)
{
var model = new ParameterizationViewModel();
if (String.IsNullOrEmpty(id))
{
//Code omitted
//Here, I structure my model to be a clean view
}
else
{
//Code omitted
//Here, I structure my model to be a screen filled with recovered data
}
return View(model);
}
[HttpPost]
public ActionResult Index(ParameterizationViewModel model)
{
if (!ModelState.IsValid)
{
//Here, I validate my ViewModel. I need you to get here, but it doesn't.
return View(model);
}
//Code omitted
//Here, follow the flow of persistence with WebService
}
}
查看:
@model Project.Models.Parameterization.ParameterizationViewModel
@{
ViewBag.Title = ResourcesGSC.Language.LabelParameterizationMenu;
}
@using (Html.BeginForm("", "Parameterization", FormMethod.Post, new { }))
{
<div class="form-group">
<div class="row mb-3">
<div class="col-lg-6 col-md-12">
@Html.LabelFor(m => m.Name, new { })
@Html.TextBoxFor(m => m.Name, new { @class = "form-control", placeholder = "" })
@Html.ValidationMessageFor(m => m.Name, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="row mb-3">
<div class="col">
<button type="submit" class="btn btn-primary float-right">
@ResourcesGSC.Language.LabelBtnSave
</button>
</div>
</div>
}
我不明白会发生什么。我在其他几个部分有相同的代码,效果很好。
我已经搜索了所有我得到的东西,但我无法解决它......
有人可以帮忙解决这个问题吗?
此外,验证消息会显示在屏幕上。但我无法访问我的控制器,因为它发生在其他屏幕上
【问题讨论】:
-
那么有效的虚拟机确实可以进入您的控制器吗?是您不想要的客户端验证吗?
-
是的,如果我的虚拟机有效,它会到达我的控制器。我不知道如何准确地向你解释。发生客户端验证,但我需要它首先到达我的控制器。我想我可以说我不想要 Fail Fast Validation 之类的东西,我认为这就是正在发生的事情......我不知道这对你是否有意义,但如果你得到了,我可以尝试更好地解释它困惑。
-
您可以尝试将
HtmlHelper.ClientValidationEnabled = false;添加到您的视图中(在ViewBag.Title部分应该没问题),看看它是否得到您期望的结果? -
它的工作!谢谢zgood !!!你能给我解释一下为什么吗?我的项目中有很多其他视图,我不必这样做并且按预期工作。只有这种观点让我陷入困境..
-
错过了 3 分钟...哈哈。
标签: asp.net .net asp.net-mvc-5