【问题标题】:Problem with HiddenFor helperHiddenFor 助手的问题
【发布时间】:2015-06-08 06:26:34
【问题描述】:

型号:

public sealed class Model
{
    public string Value { get; set; }
}

控制器:

[HandleError]
public class HomeController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        return View(new Model { Value = "+" } );
    }

    [HttpPost]
    public ActionResult Index(Model model)
    {
        model.Value += "1";
        return View(model);
    }
}

查看:

<%using (Html.BeginForm()){%>
  <%: Model.Value %>
  <%: Html.HiddenFor(model => model.Value) %>
  <input type="submit" value="ok"/>
<%}%>

我每次提交表单的结果都是

<form action="/" method="post">+1
<input id="Value" name="Value" type="hidden" value="+">
<input type="submit" value="ok">
</form>

这意味着 HiddenFor 帮助器不使用 Model.Value 的实际值,而是使用传递给控制器​​一。它是 MVC 框架中的错误吗?有人知道解决方法吗?

更新: EditerFor 的工作方式类似。

【问题讨论】:

标签: c# asp.net-mvc


【解决方案1】:

这将解决您的问题,但不是推荐的解决方案。

更多信息可以在这里找到:http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx

[HttpPost]
public ActionResult Index(Model model)
{
    model.Value += "1";

    ModelState.Clear();

    return View(model);
}

[编辑]

如果您不想使用&lt;input id="Value" name="Value" type="hidden" value="&lt;%: Model.Value %&gt;"/&gt;,另一种选择

[HttpPost]
public ActionResult Index(FormCollection collection)
{
    var m = new Model();

    m.Value = collection["Value"] + "1";

    return View(m);
}

【讨论】:

  • 你读过这篇文章吗?使用&lt;input id="Value" name="Value" type="hidden" value="&lt;%: Model.Value %&gt;"/&gt; 而不是ModelState.Clear();
  • 好吧,如果你清除了 ModelState,你就会摆脱用户在出现一些错误时输入的所有数据。 HTML中的HTML有什么问题?
  • 不好的是我们不能使用有用的辅助方法。意思就是我们应该自己生成id和name属性,比如。
猜你喜欢
  • 1970-01-01
  • 2016-12-06
  • 2011-01-07
  • 1970-01-01
  • 2021-07-10
  • 1970-01-01
  • 2011-02-15
  • 2014-05-27
  • 2010-12-19
相关资源
最近更新 更多