2

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
  • $.post('/Search?query=' + query); Commented May 23, 2013 at 8:53
  • Cast the query string to object. return View((object)query); Commented May 23, 2013 at 9:04

2 Answers 2

3
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

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.
1

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

This doesn't redirect me to my "Index" view of the "Search" view to show the results, does it?
@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.
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!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.