我如何从一个ActionFilter访问的ModelState? [英] How do I access the ModelState from an ActionFilter?

查看:199
本文介绍了我如何从一个ActionFilter访问的ModelState?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立一个 ActionFilter 来重用某些code一个简单的垃圾块 - 基本上是我做的是,我有一个呈现一个输入文本框和一个隐藏的输入,并在ActionFilter我检查两个值是否相同或不HTML辅助方法。如果没有,我希望利用我的验证逻辑的其余部分,添加 ModelStateError 的ModelState ,但怎么办是我做的?如何添加一个 ModelStateError 从whithin的 ActionFilter

I'm building an ActionFilter to reuse some code for a simple spam block - basically what I do is that I have a Html Helper method that renders an input textbox and a hidden input, and in the ActionFilter I check whether the two values are the same or not. If not, I want to leverage the rest of my validation logic and add a ModelStateError to the ModelState, but how do I do that? How do I add a ModelStateError from whithin the ActionFilter?

更新:这里的code我与尝试。当我测试具有此属性的控制器动作, ModelState.IsValid 仍然返回真正即使我不及格任何形式的值要求:

UPDATE: Here's the code I'm trying with. When I test a controller action that has this attribute, ModelState.IsValid still returns true even though I don't pass any of the form values required:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
	var r = filterContext.HttpContext.Request;
	if (r.Form["sixtimesnine"] != r.Form["fourtytwo"] || string.IsNullOrEmpty(r.Form["sixtimesnine"]) || string.IsNullOrEmpty(r.Form["fourtytwo"]))
	{
		filterContext.Controller.ViewData.ModelState.AddModelError("Spam", this.ErrorMessage);
	}
	base.OnActionExecuting(filterContext);
}

这是 ActionMethod

[ValidateAntiSpam(ErrorMessage = "Spambotar får inte.")]
public ActionResult Write(GuestbookPost postToCreate)
{
	if (ModelState.IsValid)
	{
		_posts.Add(postToCreate);
		return RedirectToAction("Index");
	}
	return View();
}

我只注意到,如果我将 OnActionExecuting 方法中的断点,然后点击调试测试,断点永远不会命中。为什么呢?

I just noticed that if I set a breakpoint inside the OnActionExecuting method and hit "Debug tests", the breakpoint is never hit. Why?

推荐答案

这将是:
filterContext.Controller.ViewData.ModelState

这篇关于我如何从一个ActionFilter访问的ModelState?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆