【问题标题】:Does Html.TextBox uses Request.Params instead of Model?Html.TextBox 是否使用 Request.Params 而不是 Model?
【发布时间】:2009-06-04 21:52:28
【问题描述】:

我有一个简单的测试应用程序:

型号:

public class Counter
{
    public int Count { get; set; }

    public Counter()
    {
        Count = 4;
    }
}

控制器:

public class TestController : Controller
{
    public ActionResult Increment(Counter counter)
    {
        counter.Count++;
        return View(counter);
    }
}

查看:

<form action="/test/increment" method="post">
    <input type="text" name="Count" value="<%= Model.Count %>" />
    <input type="submit" value="Submit" /> 
</form>

点击提交我得到这样的值:

5, 6, 7, 8, ...

对于 Html.TextBox,我期望相同的行为

<form action="/test/increment" method="post">
    <%= Html.TextBox("Count") %>
    <input type="submit" value="Submit" /> 
</form>

但实际上得到了

5、5、5、5。

似乎 Html.TextBox 使用 Request.Params 而不是 Model?

【问题讨论】:

    标签: asp.net-mvc html-helper


    【解决方案1】:

    Html.TextBox() 在内部使用 ViewData.Eval() 方法,该方法首先尝试从字典 ViewData.ModelState 中检索值,然后从 ViewData.Model 的属性中检索值。这样做是为了允许在提交无效表单后恢复输入的值。

    从 ViewData.ModelState 字典中移除 Count 值有帮助:

    public ActionResult Increment(Counter counter)
    {
        counter.Count++;
        ViewData.ModelState.Remove("Count");
        return View(counter);
    }
    

    另一种解决方案是为 GET 和 POST 操作制作两种不同的控制器方法:

    public ActionResult Increment(int? count)
    {
        Counter counter = new Counter();
    
        if (count != null)
            counter.Count = count.Value;
    
        return View("Increment", counter);
    }
    
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Increment(Counter counter)
    {
        counter.Count++;
    
        return RedirectToAction("Increment", counter);
    }
    

    Counter 对象也可以通过 TempData 字典传递。

    您可能还对 Stephen Walther 的文章 Repopulate Form Fields with ViewData.Eval() 感兴趣。

    【讨论】:

    • 那为什么明确指定 Model.Count 不起作用?
    • 因为起初 Html.TextBox() 从 ModelState 字典中获取值。
    【解决方案2】:

    这不是这里的问题。指定

    <%= Html.TextBox("Count") %>
    

    相当于指定

    <%= Html.TextBox("Count", null) %>
    

    这将从 ModelStateDictionary 中提取匹配值(名为“Count”)。

    但即便如此,显式传入

    <%= Html.TextBox("Count", Model.Count) %>
    

    导致与 alex2k8 描述的行为相同。

    【讨论】:

      【解决方案3】:

      Html.TextBox的参数多于一个..第一个参数是输入元素的名称或id,第二个是值...

      所以像这样写你的文本框助手:

      <%= Html.TextBox("Count",Model.Count) %>
      

      干杯

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-21
        • 2013-10-11
        • 2021-09-22
        • 2021-09-04
        • 1970-01-01
        相关资源
        最近更新 更多