文本框的值不随 ViewBag 改变

The value of the textbox doesn't change with ViewBag

我写了一个简短的程序,但没有得到预期的结果。考虑这个视图,它只是一个带有两个文本框和一个提交按钮的表单:

@{ 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" />
}

这是我的控制器:

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

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

基本上,我试图在有人单击提交按钮时切换 textbox1 和 textbox2 的内容。但无论我尝试什么,它都不起作用(即值保持原样)。起初我以为 ?? 可能与它有关,但我用 ?? 注释掉了这些行,但仍然得到相同的结果。而不是只做 return view() 我尝试了 return view("index", ViewBag) 但这没有任何区别。有人知道我在这里做错了什么吗?

以下是需要在控制器上完成的操作。说这么简单的任务罗嗦:

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

只需清除模型状态即可。将您的 POST 方法替换为以下代码:

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