Asp.net mvc 如何更新文本框值
我的视图中有一个文本框。我在文本框中输入一个数字,然后我希望控制器将该数字相乘,并将结果放入文本框 我该怎么做 这是我已经做过的。 让我们从视图开始:Asp.net mvc 如何更新文本框值,asp.net-mvc,html-helper,Asp.net Mvc,Html Helper,我的视图中有一个文本框。我在文本框中输入一个数字,然后我希望控制器将该数字相乘,并将结果放入文本框 我该怎么做 这是我已经做过的。 让我们从视图开始: <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.or
<%@ 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>
但是什么也没发生。是的,我看到这篇文章正在完成,编码的步骤进入了public ActionResult Index(int number)
。我看到这个数字是从文本框中取出来的,它被正确地乘以了
如您所见,我尝试过使用ViewData。我还使用了TempData。
这是我尝试过的视图中文本框的另一个代码:
<%=Html.TextBox("number", ViewData["number"])%>
但这并不重要。文本框不会用新值更新。我该怎么做呢?试试看
[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>验证失败>返回视图,因此显示用户输入的数据是预期行为 试试看
[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>验证失败>返回视图,因此显示用户输入的数据是预期行为