问题描述
我有一个简单的测试应用程序:
I have a simple test application:
型号:
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>
点击提交,我得到这样的值:
Clicking Submit I get such values:
5,6,7,8,...
使用Html.TextBox我预料的一样的行为
With Html.TextBox I expected the same behaviour
<form action="/test/increment" method="post">
<%= Html.TextBox("Count") %>
<input type="submit" value="Submit" />
</form>
但实际上得到了
5,5,5,5
这似乎Html.TextBox使用替代型号Request.Params?
It seems Html.TextBox uses Request.Params instead of Model?
推荐答案
Html.TextBox()内部使用ViewData.Eval()方法首先试图从字典中ViewData.ModelState旁边的值来检索值所述ViewData.Model的属性。这样做是为了让恢复无效的表格后,输入的数值提交。
Html.TextBox() uses internally ViewData.Eval() method which first attempts to retrieve a value from the dictionary ViewData.ModelState and next to retrieve the value from a property of the ViewData.Model. This is done to allow restoring entered values after invalid form submit.
从ViewData.ModelState字典中删除计数值帮助:
Removing Count value from ViewData.ModelState dictionary helps:
public ActionResult Increment(Counter counter)
{
counter.Count++;
ViewData.ModelState.Remove("Count");
return View(counter);
}
另一种解决方案是使对GET两种不同的控制器方法和POST操作
Another solution is to make two different controller methods for GET and POST operations:
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);
}
计数器对象还可以通过TempData的字典过去了。
Counter object could also be passed via TempData dictionary.
您还可能有兴趣的文章Repopulate表单域ViewData.Eval()由斯蒂芬·瓦尔特的。
You may also be interested in the article Repopulate Form Fields with ViewData.Eval() by Stephen Walther.
这篇关于是否Html.TextBox使用Request.Params,而不是模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!