简体   繁体   中英

Calling view from JavaScript

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM