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?

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

Sign up to request clarification or add additional context in comments.

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

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

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.