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

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

问题描述

我可能遗漏了一些非常明显的东西,但我想做的只是有一个简单的表单,允许它发布,更改其中一个字段,当它返回时它应该向我显示更改后的值.很简单吧?

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# 版本:

For earlier C# versions:

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

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

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