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?
you can just call :
ModelState.Clear();
return View(YourModel);
this will clear all ModelState values
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";
Note: This is only a problem if you are using ASP.NET input controls. For example, if your HTML contains
<p>@model.Field1</p>
Then you can update Field1 in the controller
[HttpPost]
public IActionResult Test(TestModel model)
{
model.Field1 = "changed"; // this will update as expected
return View(model);
}
You only need to use the solution given by Vadent when your HTML contains
<input asp-for="Field1" class="form-control" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With