MVC取消绑定操作参数

MVC取消绑定操作参数

本文介绍了ASP.NET MVC取消绑定操作参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能从跨请求保持其价值禁用某个动作参数?

Is it possible to disable a certain action parameter from retaining its value across requests?

[HttpPost]
public ActionResult MyAction(string value1, string value2)
{
        if(value1=="hi")
             ModelState.AddModelError("value1", "Can't have hi");
        //do stuff
        if(ModelState.IsValid)
           return RedirectToAction("Finish");
        else
           return View()
}


[HttpGet]
public ActionResult MyAction()
{
        return View()
}

该视图由一个简单的形式与两个输入框(值1和值2)的。一旦提交,验证失败,则返回视图。我想总是在视图中的文本框的值是空的。

The view consists of a simple form with two input boxes (value1 and value2). Once submitted and validation fails, the view is returned. I want to always have the value of the textbox in the view to be empty.

有关文本框值1的值,如果该模型是无效的保留。

The value for the textbox "value1" is retained if the the model is invalidated.

我想声明的文本框为<%= Html.TextBox(值1,NULL)%>,但该值仍然保留。我还试图用[绑定(不包括=值1)],但对单个变量这么想的工作。

I tried to declare the textbox as <%= Html.TextBox("value1", null) %> but the value is still retained. I also tried to use [Bind(Exclude="value1")] but that dosen't work on a single variable.

更新2:

我这样做是因为这是用于验证码(定制方案)输入文本框。我想文本框要清除的页面加载任何时候,但我想确认留下来。

I'm doing this for a textbox that is used for Captcha (custom solution) input. I want the textbox to be cleared any time the page is loaded, but I want validation to remain.

推荐答案

尝试调用

ModelState["value1"].Value
  = new ValueProviderResult(null, string.Empty, CultureInfo.InvariantCulture);

您从您的控制器操作中返回视图之前。

before you return the view from within your controller action.

这样做的结果是保持与关键值1相关联的所有错误,但有一个空值替换的值。

What this does is keep all the errors associated with the key "value1", but replaces the value with an empty value.

这篇关于ASP.NET MVC取消绑定操作参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 22:17