MVC5视图模型的验证无法到达控制器



我有一个Asp。Net MVC5项目,其中在ViewModel上使用requires属性时,如果ViewModel无效,我将无法访问我的控制器。但是,它只发生在特定的屏幕上。

我需要,即使使用了错误的VM,这个请求也会到达我的控制器,以便在我的视图中发生另一个操作(在这种情况下,隐藏了一个微调器(。

我的代码示例:

ViewModel:

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>
}

我不明白发生了什么。我在其他几个部分都有相同的代码,它们运行得很好。

我已经搜索了所有我得到的东西,但我无法解决它…

有人能在这个问题上帮忙吗?

此外,屏幕上还会显示验证消息。但我无法访问我的控制器,因为它发生在其他屏幕上

客户端验证似乎在你不希望的时候阻碍了你。默认情况下,如果你使用MVC样板代码,它会自动设置并打开表单的客户端验证。这将在javascript中验证客户端上的必填字段等内容,并阻止表单在未通过客户端验证的情况下发布到服务器。

你可以在这里阅读它的工作原理:https://www.blinkingcaret.com/2016/03/23/manually-use-mvc-client-side-validation/(本文介绍了如何手动使用它,但很好地解释了它的工作原理(

但是,如果您想在控制器中处理所有服务器端验证,可以通过以下几种方式禁用客户端验证:

  • 在捆绑包配置中删除对jquery.validate.jsjquery.validate.unobtrusive.js的脚本引用

  • <add key="ClientValidationEnabled" value="false"/><add key="UnobtrusiveJavaScriptEnabled" value="false"/>添加到<appSettings>节点下的weeb.config中

  • HtmlHelper.ClientValidationEnabled = false;HtmlHelper.UnobtrusiveJavaScriptEnabled = false;添加到各个视图或操作中

不要使用jQuery验证器。它将检查验证错误,并且在验证失败的情况下不会让请求到达您的控制器。既然你说客户端验证正在进行,我只能猜测情况确实如此。禁用jQuery验证器,即使您的视图模型无效,请求也会到达控制器。

如果您使用了mvc 5项目的默认模板,那么请在bundle.config文件中查找它。在那里你可以评论出来。

最新更新