Call javascript from MVC controller action

后端 未结 9 1276
半阙折子戏
半阙折子戏 2021-02-01 07:04

Can I call javascript function from MVC controller action (not from view page) and get return value? How?


I need to make request to server

9条回答
  •  心在旅途
    2021-02-01 07:31

    If I understand correctly the question, you want to have a JavaScript code in your Controller. (Your question is clear enough, but the voted and accepted answers are throwing some doubt) So: you can do this by using the .NET's System.Windows.Forms.WebBrowser control to execute javascript code, and everything that a browser can do. It requires reference to System.Windows.Forms though, and the interaction is somewhat "old school". E.g:

    void webBrowser1_DocumentCompleted(object sender, 
        WebBrowserDocumentCompletedEventArgs e)
    {
        HtmlElement search = webBrowser1.Document.GetElementById("searchInput");
        if(search != null)
        {
            search.SetAttribute("value", "Superman");
            foreach(HtmlElement ele in search.Parent.Children)
            {
                if (ele.TagName.ToLower() == "input" && ele.Name.ToLower() == "go")
                {
                    ele.InvokeMember("click");
                    break;
                }
            }
        }
    }
    

    So probably nowadays, that would not be the easiest solution.

    The other option is to use Javascript .NET or jint to run javasctipt, or another solution, based on the specific case.

    Some related questions on this topic or possible duplicates:

    Embedding JavaScript engine into .NET

    Load a DOM and Execute javascript, server side, with .Net

    Hope this helps.

提交回复
热议问题