ASP.NET Core-发布后更改表单值

问题描述:

我可能会遗漏一些非常明显的东西,但是我想要做的就是拥有一个简单的表单,允许它进行POST,更改其中一个字段,当它返回时,应该向我显示更改后的值.很简单,对吧?

I'm probably missing something very obvious, but all I'm trying to do is have a simple form, allow it to POST, change one of the fields, and when it returns it should show me the changed value. Simple, right?

模型如下:

public class TestModel
{
    public string Field1 { get; set; }
    public string Field2 { get; set; }
}

控制器动作:

public IActionResult Test()
{
    return View(new TestModel());
}

[HttpPost]
public IActionResult Test(TestModel model)
{
    model.Field1 = "changed"; // this seems to be ignored
    return View(model);
}

视图:

@model AspNetCoreTest1.Models.TestModel
<form method="post" asp-controller="Home" asp-action="Test">
    <input asp-for="Field1" />
    <br />
    <input asp-for="Field2" />
    <br />
    <button type="submit">Send</button>
</form>

我可以看到该表格并将其回发(我可以看到我在模型中键入的值),但是在POST之后,该表格仍显示我键入的值.对于第一个字段,它不会显示changed.

I can see the form and it POSTs back (I can see the values I typed in the model), but after the POST the form still shows the values I typed. It does NOT show changed for the first field.

(我正在使用ASP.NET Core 1.1)

(I'm using ASP.NET Core 1.1)

有想法吗?

我们无法直接对传递的模型进行更改,并希望它会反映在UI中.您的问题的解决方案如下.

We can't directly make changes to the model which is passed and hope for that it will reflect in UI. The solution for your problem is as follows.

如果使用的是C#6.0,请用以下代码替换代码行model.Field1 = "changed";:

Replace this line of code model.Field1 = "changed"; with following if you are using C# 6.0:

ModelState.FirstOrDefault(x => x.Key == nameof(model.Field1)).Value.RawValue = "changed";

对于早期的C#版本:

ModelState.FirstOrDefault(x => x.Key == "Field1")).Value.RawValue = "changed";