ASP.NET MVC - Html.TextBox - Value not set via ViewData dictionary

I have a search box on a page (actually in a partial view, although this is not necessary), with an Html.TextBox control.

<%= Html.TextBox("query", ViewData["query"], new { style = "width: 90%;" })%> 

The action method takes a โ€œrequestโ€ as a parameter, and I edit this value to clear the line that was passed:

 public ActionResult SearchQuery(string query) { ViewData["query"] = StringFunctions.ProperCasing(query.Replace("_", " ")); 

However, when it gets into the Html.TextBox, the original value of the request (in this case with an underscore) is preserved. I see that the edited value is in the ViewData field, for example, if:

 query == "data_entry" 

then after passing to the action method

 ViewData["query"] == "data entry" 

but the value when it reaches the view in the Html.TextBox is still "data_entry". It appears that there is a collision between the query action method parameter and the query query window form parameter. Does anyone know what is going on here, or is there another way to convey the meaning?

This action method is separate from the action that occurs when publishing search box data.

+4
source share
2 answers

Html.Textbox helper looks for the ModelState first ( ASP.NET MVC source , InputExtensions.cs 183 line, HtmlHelper.cs 243 line). The simplest solution is to remove the ModelState for the "request":

 public ActionResult SearchQuery(string query) { ViewData["query"] = StringFunctions.ProperCasing(query.Replace("_", " ")); ModelState.Remove("query"); return View(); } 
+5
source

I donโ€™t know if this is a problem, but first of all I want to transfer the viewing data to the controller.

 public ActionResult SearchQuery(string query) { ViewData["query"] = StringFunctions.ProperCasing(query.Replace("_", " ")); return view(ViewData): } 
0
source

All Articles