ASP.NET Core - Changing form values after a post

北慕城南 提交于 2019-12-01 17:41:56

问题


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?


回答1:


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";



回答2:


you can just call :

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

this will clear all ModelState values




回答3:


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" />


来源:https://stackoverflow.com/questions/41775756/asp-net-core-changing-form-values-after-a-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!