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

耗尽温柔 提交于 2019-12-12 09:43:47

问题


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("_", " "));  

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"

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.


回答1:


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();
}



回答2:


Dont know if this is the problem but my first thought is is to pass the view data back in the controller.

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


来源:https://stackoverflow.com/questions/1241682/asp-net-mvc-html-textbox-value-not-set-via-viewdata-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!