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?
The model looks like this:
public class TestModel
{
public string Field1 { get; set; }
public string Field2 { get; set; }
}
The controller actions:
public IActionResult Test()
{
return View(new TestModel());
}
[HttpPost]
public IActionResult Test(TestModel model)
{
model.Field1 = "changed"; // this seems to be ignored
return View(model);
}
The view:
@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>
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.
(I'm using ASP.NET Core 1.1)
Thoughts?
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.
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";
For earlier C# versions:
ModelState.FirstOrDefault(x => x.Key == "Field1")).Value.RawValue = "changed";