简体   繁体   English

从JavaScript调用视图

[英]Calling view from JavaScript

I've got a JavaScript function defined like this: 我有一个像这样定义的JavaScript函数:

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. 现在我想用SearchController中的查询文本调用View“Search”。 How can I do that? 我怎样才能做到这一点?

When doing this, no view is shown: 执行此操作时,不显示任何视图:

SearchController.cs: 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? 如何将查询参数传递给我的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 然后你的MVC将知道query是一个模型而不是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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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