【问题标题】:How to update textbox value如何更新文本框值
【发布时间】:2013-08-31 07:57:51
【问题描述】:

我的视图中有一个文本框。我在文本框中输入一个数字,然后我希望控制器将数字相乘并将结果放入文本框中。

我该怎么做?

这是我已经做过的。 让我们从视图开始:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <html xmlns="http://www.w3.org/1999/xhtml" >
            <head runat="server">
                <title>Index</title>
            </head>
            <body>
                <div>
                    <h2>Please enter a number</h2>

                    <% using (Html.BeginForm()) { %>

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

                        <input type="submit" value="Index" name ="Index" />

                    <% } %>
                </div>
            </body>
        </html>

如您所见,我有一个简单的文本框和按钮。

这是我的控制器:

using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(int number)
        {
            number = number * 2;
            ViewData["number"] = number;
            return View(ViewData);
        }
    }
}

但实际上什么也没发生。是的,我看到帖子正在完成,编码步骤进入public ActionResult Index(int number)。我看到数字是从文本框中获取的,它的乘法正确。

如您所见,我已尝试使用 ViewData。我也使用过 TempData。 这是我尝试过的视图中文本框的另一个代码:

<%=Html.TextBox("number", ViewData["number"])%>

不过没关系。文本框不会使用新值进行更新。我该怎么做?

【问题讨论】:

    标签: asp.net-mvc html-helper


    【解决方案1】:

    试试

        [HttpPost]
        public ActionResult Index(int number)
        {
            number = number * 2;
            ViewData["id"] = number;
            ModelState.Clear(); // this is the key, you could also just clear ModelState for the id field
            return View(ViewData);
        }
    

    您也可以只使用常规的 html 输入而不是 HtmlHelper,这样您的代码就会按预期工作。

    Html 助手的默认行为是咬你。在使用 ViewData 中的内容之前,它会在 ModelState 集合中查找数据。推理是正常情况是 POST > Validation Fail > Return View,因此显示用户输入的数据是预期的行为。

    【讨论】:

      猜你喜欢
      • 2011-03-06
      • 2020-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多