ASP.NET Core-发布后更改表单值 [英] ASP.NET Core - Changing form values after a post

查看:142
本文介绍了ASP.NET Core-发布后更改表单值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能会遗漏一些非常明显的东西,但是我想要做的就是拥有一个简单的表单,允许它进行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?

模型如下:

public class TestModel
{
    public string Field1 { get; set; }
    public string Field2 { get; set; }
}

控制器动作:

public IActionResult Test()
{
    return View(new TestModel());
}

[HttpPost]
public IActionResult Test(TestModel model)
{
    model.Field1 = "changed"; // this seems to be ignored
    return View(model);
}

视图:

@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>

我可以看到该表格并将其回发(我可以看到我在模型中键入的值),但是在POST之后,该表格仍显示我键入的值.对于第一个字段,它不会显示changed.

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.

(我正在使用ASP.NET Core 1.1)

(I'm using ASP.NET Core 1.1)

有想法吗?

推荐答案

我们无法直接对传递的模型进行更改,并希望它会反映在UI中.您的问题的解决方案如下.

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.

如果使用的是C#6.0,请用以下代码替换代码行model.Field1 = "changed";:

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

对于早期的C#版本:

ModelState.FirstOrDefault(x => x.Key == "Field1")).Value.RawValue = "changed";

这篇关于ASP.NET Core-发布后更改表单值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆