ASP.NET Core - Changing form values after a post

自古美人都是妖i 提交于 2019-12-01 17:33:23
Vedant

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

you can just call :

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

this will clear all ModelState values

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