MVC5
Using the information from this CKEditor documentation I was eventually able to integrate an image selection process from an MVC method/view that displays a list of available images that could be inserted into a text area using CKEditor.
While the finished solution turned out to be preciously simple, the overall process was not particularly intuitive. I will eventually post my solution as I am certain many relatively new MVC coders, such as myself, are looking for simple and straightforward solutions for this functionality. But in the meantime,
The code below shows the relevant lines from Example 2 at the link above, slightly rearranged.
<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>
I never figured out how to use getUrlParam(). I eventually just bypassed it and fed-through the variable funcNum with the exact parameter that had been passed into my image selector method. As soon as I did that, the sample code from CKEditor worked great.
But what is that getUrlParam() function doing? I only nominally understand RegExp, and this one completely escapes me. Can anyone explain why it is even suggested?
The
getUrlParam
takes aparamName
(asq
inhttp://google.com/search.php?q=term
), defines aRegExp
that matches theparam
and captures its value into Group 1 (match[1]
, e.g.term
) that is returned by the method. Thewindow.location.search
gets the querystring part (e.g.?q=term
) of a current window URL in JS.I'd replace the regex definition with a simpler
The resulting regex will look like
[?&]q=([^&]+)
matching:[?&]
- either a?
or&
(in your original code, it is(?:[\?&]|&)
, matching either a?
or&
, or a&
- thus, I suggest shortening)q=
- literal sequence of charactersq=
([^&]+)
- Group 1 capturing one or more characters other than&
.In VB.NET, you could use something like:
And call with
Dim res As String = getUrlParam("q")
.