I've got a JavaScript function defined like this:
function onQuickSearchClick(s) {
var query = s.GetText();
$.post('/Search/', { query: query });
}
Now I want to call the View "Search" with the query-text in the SearchController. How can I do that?
When doing this, no view is shown:
SearchController.cs:
public ActionResult Index(string query)
{
// Can't do "return View(query)" here, because this would be interpreted as the view name
return View();
}
How can I pass the query parameter to my Views/Search/Index.cshtml?
Mathew Thompson
56.5k15 gold badges130 silver badges151 bronze badges
asked May 23, 2013 at 8:49
2 Answers 2
function onQuickSearchClick(s) {
var query = s.GetText();
window.location = '@Url.Action("Index", "Search")?query=' + query;
/* OR
window.location = 'Search/Index?query=' + query;
*/
//$.post('/Search/', { query: query });
}
I think I did not understood. You can return string as model like this:
public ActionResult Index(string query)
{
return View((object)query);
}
Then your MVC will know query
is a model not viewName
answered May 23, 2013 at 9:00
1 Comment
SeToY
You understood quite well. Was I was missing was the redirect of
window.location = '@Url.Action("Index", "Search")
. I thought this would be done by simply specifying the View in the ActionResult
. Apparently, I was wrong.You'd have to use the three parameter overload for that.
The first parameter is view name, the second is master view name, the last is the model.
return View("Index", "", query);
answered May 23, 2013 at 8:52
3 Comments
SeToY
This doesn't redirect me to my "Index" view of the "Search" view to show the results, does it?
Mathew Thompson
@SeToY You can change that first parameter to be whichever view you want, I just took a guess at the view you wanted to return.
SeToY
Thank you, it was just about the
window.location = '@Url.Action("Index", "Search")
that AliRıza Adıyahşi managed to figure out. I voted you both up, though, because your "three parameter overload" also needed to be done instead of casting to object
:) Thanks!default
$.post('/Search?query=' + query);
query
string to object.return View((object)query);