Search code examples
asp.netasp.net-mvcasp.net-mvc-4viewbag

The value of the textbox doesn't change with ViewBag


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?


Solution

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