Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core - Changing form values after a 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?

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?

like image 657
pbz Avatar asked Jan 21 '17 04:01

pbz


3 Answers

you can just call :

ModelState.Clear();
return View(YourModel);

this will clear all ModelState values

like image 81
Ahmed Fouad Avatar answered Nov 03 '22 22:11

Ahmed Fouad


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";
like image 29
Vedant Avatar answered Nov 03 '22 21:11

Vedant


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" />
like image 1
wpqs Avatar answered Nov 03 '22 21:11

wpqs