MVC5

使用来自CKEditor documentation的信息,我最终能够从MVC方法/视图集成图像选择过程,该过程显示可使用CKEditor插入文本区域的可用图像列表。

虽然最终的解决方案非常简单,但是整个过程并不是特别直观。我最终将发布我的解决方案,因为我可以肯定许多相对较新的MVC编码人员(例如我自己)正在为该功能寻求简单明了的解决方案。但与此同时,

下面的代码在上面的链接中显示了示例2中的相关行,并对其进行了重新排列。

<body>
  <button onclick="returnFileUrl()">Select File</button>
</body>

<script>
    function getUrlParam( paramName ) {    // Helper function to get parameters from the query string.
        var reParam = new RegExp( '(?:[\?&]|&)' + paramName + '=([^&]+)', 'i' );
        var match = window.location.search.match( reParam );
        return ( match && match.length > 1 ) ? match[1] : null;
    }

    function returnFileUrl() {    // Simulate user action of selecting a file to be returned to CKEditor
        var funcNum = getUrlParam( 'CKEditorFuncNum' );
        var fileUrl = '/path/to/file.txt';
        window.opener.CKEDITOR.tools.callFunction( funcNum, fileUrl );
        window.close();
    }
</script>


我从来没有想过如何使用getUrlParam()。我最终只是绕过它,并使用传递到我的图像选择器方法中的确切参数来传递变量funcNum。我这样做后,来自CKEditor的示例代码就很好用了。

但是,getUrlParam()函数在做什么?我只名义上了解RegExp,而这完全使我逃脱了。谁能解释为什么甚至建议这样做?

最佳答案

getUrlParam接受一个paramName(如q中的http://google.com/search.php?q=term),定义一个与RegExp匹配的param并将其值捕获到组1(match[1],例如term)中,方法返回的值。 window.location.search获取JS中当前窗口URL的查询字符串部分(例如?q=term)。

我将用更简单的正则表达式定义替换

var reParam = new RegExp( '[?&]' + paramName + '=([^&]+)', 'i');


生成的正则表达式将类似于[?&]q=([^&]+)匹配项:


[?&]-?&(在您的原始代码中,它是(?:[\?&]|&),与?&&匹配-因此,我建议缩短)
q=-字符的文字序列q=
([^&]+)-组1捕获除&以外的一个或多个字符。


在VB.NET中,您可以使用类似以下内容的东西:

Private Shared Function getUrlParam(paramName As String) As String
    Dim reParam = "(?i)[?&]" & Regex.Escape(paramName) & "=([^&]+)"
    Dim match As Match = Regex.Match("http://google.com/index.php?q=term", reParam)
    If match.Success = True And match.Value.Length > 1 Then
        Return match.Groups(1).Value
    Else
        Return String.Empty
    End If
End Function


并用Dim res As String = getUrlParam("q")调用。

09-25 21:29