ASP.NET MVC-Html.TextBox-未通过ViewData字典设置值 [英] ASP.NET MVC - Html.TextBox - Value not set via ViewData dictionary
问题描述
我在一个带有Html.TextBox控件的页面上有一个搜索框(实际上是部分视图,尽管不确定是否相关).
I have a search box on a page (actually in a partial view though not sure that is relevant) with an Html.TextBox control.
<%= Html.TextBox("query", ViewData["query"], new { style = "width: 90%;" })%>
该操作方法将查询"作为参数,然后编辑此值以清除传入的字符串:
The action method takes "query" as a parameter, and I edit this value to clean up the string that is passed in:
public ActionResult SearchQuery(string query) {
ViewData["query"] = StringFunctions.ProperCasing(query.Replace("_", " "));
但是,当它到达Html.TextBox时,将保留原始查询值(在本例中为下划线).我可以看到编辑后的值位于ViewData字段中,例如,如果:
However, when it gets to the Html.TextBox the original query value (in this case with underscores) is preserved. I can see that the edited value is in the ViewData field, so for example, if:
query == "data_entry"
然后,将其传递给操作方法
then, after being passed into the action method
ViewData["query"] == "data entry"
,但是Html.TextBox中的值到达视图时仍为"data_entry".动作方法参数查询"和搜索框表单参数查询"之间似乎发生冲突.任何人都知道这里发生了什么,或者是否还有另一种方法来传递值?
but the value, when it reaches the view, in the Html.TextBox is still "data_entry". It seems like there is a collision between the action method parameter "query" and the search box form parameter "query". Anyone know what is going on here or if there is another way to pass the value?
此操作方法与发布搜索框数据所导致的操作不同.
This action method is separate from the action that results from posting the search box data.
推荐答案
Html.Textbox
助手首先查找ModelState
(查询":
Html.Textbox
helper looks for ModelState
first (ASP.NET MVC source, InputExtensions.cs line 183, HtmlHelper.cs line 243). The simplest solution would be removing the ModelState
for "query":
public ActionResult SearchQuery(string query)
{
ViewData["query"] = StringFunctions.ProperCasing(query.Replace("_", " "));
ModelState.Remove("query");
return View();
}
这篇关于ASP.NET MVC-Html.TextBox-未通过ViewData字典设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!