代码之家  ›  专栏  ›  技术社区  ›  Liam

Html.EditorFor 发布后不更新[重复]

  •  1
  • Liam  · 技术社区  · 6 年前

    我做错了什么。我已经为我的问题创建了一个简单的例子。

    我有一个简单的类如下:

    public class Example
    {
        public string Text { get; set; }
    }
    

    我在我的控制器上创建了两个方法

    这是您点击的查看页面。它创造了一个新的 Example 对象。

    public ActionResult Example()
    {
        var model = new Example {
           Text = "test"
        };
        return View(model);
    }
    

    [HttpPost, ValidateAntiForgeryToken]
    public ActionResult Example(Example model)
    {
        model.Text += "a";
        return View(model);
    }
    

    @model Stackoverflow.Example
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        <h1>@Model.Text</h1>
        @Html.EditorFor(model => model.Text);
        <input type="submit" value="Save" />
    }
    

    当我第一次访问页面时,标题和文本框具有相同的值

    enter image description here

    enter image description here

    为什么 @Html.EditorFor(model => model.Text); 不获取更新值?

    2 回复  |  直到 6 年前
        1
  •  1
  •   TanvirArjel    6 年前

    当您将模型发布回 ActionResult View ModelState . 这个 包含有效/无效字段以及实际 POSTed

    [HttpPost, ValidateAntiForgeryToken]
    public ActionResult Example(Example model)
    {
        ModelState.Clear(); 
        model.Text += "a";
        return View(model);
    }
    

    [HttpPost, ValidateAntiForgeryToken]
    public ActionResult Example(Example model)
    {
        var newValue = model.Text += "a";
        ModelState["Text"].Value = new ValueProviderResult(newValue,newValue, CultureInfo.CurrentCulture)
        return View(model);
    }
    
        2
  •  1
  •   Arun Kumar    6 年前

    您需要清除控制器的post方法上的模型状态

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult Example(Example model)
        {
            ModelState.Clear(); 
            model.Text += "a";
            return View(model);
        }