0

I wrote a short program but I'm not getting the expected result. Consider this view which simply is a form with two textboxes and a submit button:

@{ ViewBag.Title = "Index"; }
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
    @Html.TextBox("Box1", (string)ViewBag.TextBox1)
    @Html.TextBox("Box2", (string)ViewBag.TextBox2)
    <input type="submit" value="Search" />
}

Here's my controller:

public ActionResult Index()
{
    return View();
}

[HttpPost]
public ActionResult Index(string Box1, string Box2)
{
    ViewBag.TextBox1 = Box2;
    ViewBag.TextBox2 = Box1;
    return View("index",ViewBag);
}

Basically, I'm trying to switch the content of textbox1 and textbox2 when someone clicks the submit button. But no matter what I try it's not working (ie the values stay where they are). At first I thought may be the ?? has something to do with it but I commented out the lines with ?? but still got the same result. The instead of just doing return view() I tried return view("index", ViewBag) but that didn't make any difference. Anyone know what am I doing wrong here?

mason
  • 31,774
  • 10
  • 77
  • 121
Zuzlx
  • 1,246
  • 14
  • 33
  • 2
    Its because the vales of `Box1` and `Box2` have been added to `ModelState` in your POST method, and the html helpers use the values from `ModelState` when they exist (refer [this answer](http://stackoverflow.com/questions/26654862/textboxfor-displaying-initial-value-not-the-value-updated-from-code/26664111#26664111) for an explanation. The correct approach is to follow the PRG pattern –  Sep 11 '15 at 22:07
  • @StephenMuecke Thank you. I was totally on wrong path on that one. – Zuzlx Sep 11 '15 at 23:23

2 Answers2

3

Just clear your model state and it will work. Replace your POST method with this code:

[HttpPost]
public ActionResult Index(string Box1, string Box2)
{
    ModelState.Clear();
    ViewBag.TextBox1 = Box2;
    ViewBag.TextBox2 = Box1;
    return View();
}
Hernan Guzman
  • 1,235
  • 8
  • 14
  • @herman guzman Thank you. Accepted answer. My own answer brought fear and tears into my heart. I knew it had to be a better way. – Zuzlx Sep 12 '15 at 14:13
-2

Here's what needs to be done on the controller. Talking about wordy for such a simple task:

    [HttpPost]
    public ActionResult Index(string Box1, string Box2)
    {

        ModelState.SetModelValue("Box1", new ValueProviderResult(Box2, string.Empty, System.Globalization.CultureInfo.InvariantCulture));
        ModelState.SetModelValue("Box2", new ValueProviderResult(Box1, string.Empty, System.Globalization.CultureInfo.InvariantCulture));


        return View();
    }
Zuzlx
  • 1,246
  • 14
  • 33