Question

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

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.

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

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.

Update 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.

Was it helpful?

Solution

Try calling

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

before you return the view from within your controller action.

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

OTHER TIPS

What are you doing that's causing it to be retained? There isn't anything like ViewState in MVC that will persist a value over multiple requests unless you're writing code or using form fields to make it do so.

What does the view look like? Is this action method being called via GET or POST? What's the "do stuff" contained in your method?

Edit: You're still showing //do stuff in your example code. Does that stuff contain any references to ViewData? Your question is about binding, but I don't see any binding happening. Maybe this is beyond my understanding.

Edit 2: Glad Phil saw this one! The original question didn't mention the ModelState.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top