Converting string back to HTML - c#

I took a HTML string from tinyMCE and wrapped it with jQuery html(). I am now trying to unwrap it and display it in the the view.
I get tinyMCE contents and put them into to a div. I then extract html contents of that div and pass it to my database via AJAX. I am now trying to convert the contents back into format that will allow me to display it properly.
<textarea name="tinycontent" class="form-control"
id="textFromContentEditor" value=""></textarea>
<div id="textContent" style="display:none"></div>
var sectionContent = tinyMCE.activeEditor.getContent();
sectionContent = $('#textContent').text(sectionContent).html();
$.ajax({
url: '/Home/CreateNoteContent',
async: false,
type: 'POST',
data: {
headerID: headerID,
categoryID: categoryID,
sectionContent: sectionContent
},
success: function (result) {
if (result == false) {
toastr.error("Cannot create new content")
} else {
toastr.success("Successfully created new content")
$("#feed-" + releaseID).trigger('click');
jumpTo(scrollPos);
}
}
});
My input into tinyMCE: Hello World
What gets stored in the db: <p>Hello World</p>
I want to be able to display just the text contents in the view.

I am certainly not very good at js, ajax and so on, but this is what I did in my project to display html in one of my divs from the pages -tag.
var blobs = document.getElementById('your-div-Id').innerHTML = "<h4>somethingRandom</h4>";
OBS! I believe this is javascript and therefor might not be the right solution.
Hope this helps!

Related

Anglesharp Parse after clicking <a> which calls JavaScript function and loads additional data to page

I'm trying to parse html page that have link which loads additional data to current page.
<a href="#" data-href="/some-url/">
There a javascript function that calls after clicking on <a href="#">.
I'm able to parse data that already loaded with page, but can't parse additional block that loads by click on <a>. How can I parse all of the data including post-load data using AngleSharp?
JS code:
$('.button_add a').click(function (e) {
e.preventDefault();
var link = $(this);
var page = link.data('page');
$.ajax({
method: 'get',
url: link.data('href'),
data: {page: page},
success: function(data) {
var linkParent = link.parent();
var parentBlock = linkParent.parent();
parentBlock.children('.items').first().append(data.view);
}
});
});
Make sure to allow AngleSharp to load JS files.
var config = Configuration.Default
.WithDefaultLoader(new LoaderOptions { IsResourceLoadingEnabled = true })
.WithJs();
Keep in mind that AngleSharp.Js may not be able to deal with the complexity of the given script. Check the debug output for any exceptions.

C# MVC Upload File without overwriting previous upload

I have an
<input type="file" name="uploadedFile">
Model:
public HttpPostedFileBase UploadedFile { get; set; }
Uploading works fine, but in my "UploadedFile" after postback, there is always just the last upload.
I need to upload multiple files without selecting them all at once.
I know there is multiple="multiple" that you can add as attribute for the input, but there I would need to select all files at once.
Tried a List, no luck.
So what I need is:
Click Upload button. file prompt opens, select an image, click open, file prompt closes.
Repeat Step 1 choose another Image. No Postback has happened yet.
Send the form/do a post. Both Images should be available in the controller
Currently I just receive the second image.
Anyone can help me with this?
Kind Regards
never tested it but i think this should work for you
<input type="file" id="texboxID" name="uploadedFile[]">
Add File
<script>
function addFiles(){
$("#myForm").append('<input type="file" name="uploadedFile[]" />')
}
</script>
then uploading should be something like this:
function UploadFilesToServer(texboxID) {
var fileUpload = $("#" + texboxID+"").get(0);
var files = fileUpload.files;
var FilesToServer = new FormData();
for (var i = 0; i < files.length; i++) {
FilesToServer.append(files[i].name, files[i]);
}
$.ajax({
url: "url",
type: "POST",
contentType: false,
processData: false,
data: FilesToServer,
// dataType: "json",
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
}
hope i understood your question and answered you in a convenient way
you can store the selected files in FileList Array , then use this array to upload the files
html :
<input type="file" id="fileUpload">
jQuery:
$(document).ready(function(){
var fileArray=[];
$("#fileUpload").change(function(e){
var upFile = e.target.files[0];
fileArray.push(upFile);
console.log(fileArray);
});
})
I have tested the array it works fine , but I didn't test it in backend

ASP.NET MVC post controller get json, generate file and return it

I have an ajax post request:
function downloadElevationMap() {
var jsonData = ko.toJSON(mod.SelectedItem);
$.ajax({
url: '/Home/GetData/',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: jsonData,
success: function (data) {
console.log("OK");
},
});
}
The controller method recive data correct. The code is presented below:
public FileStreamResult GetData(Mv jsonData)
{
var resultAll = jsonData.Data.Select(d => d.y).ToList();
var str = new StringBuilder();
_fileName = "ses"+jsonData.Path;
foreach (var d in resultAll)
{
str.Append(d + " ");
}
var byteArray = Encoding.ASCII.GetBytes(str.ToString());
var stream = new MemoryStream(byteArray);
return File(stream, "text/plain", string.Format("{0}.txt", _fileName));
}
Mv - is my class that represent data. When debug the both str and stream variable contain correct data.
Function downloadElevationMap() is called by onclick="downloadElevationMap()"
I just want when downloadElevationMap() is called the GetData controller return a file for download. But simply nothing happend. Where the error is?
well you dont need ajax to do that try this
window.location="download.action?para1=value1...."
for your needs you can do some thing like this
window.location="/Home/GetData/?"+$.param(jsonData )
I'm fairly sure what you are doing is swallowing the data in the success callback in the AJAX call - all your code will do is download the file, call the success callback, and then just print "OK" to the console.
As Anto said, you don't need AJAX (and, indeed, should not be using AJAX) for this. His answer is absolutely correct, provided you can use a GET string. If you need to use a POST request, create a form with hidden inputs and submit that - something like:
HTML
<form action="/Home/GetData" method="POST" id="dataToSubmit">
<input type="hidden" name="param1" value="value1" />
<input type="hidden" name="param2" value="value2" />
<input type="hidden" name="param3.param4" value="value3" />
</form>
JS
function downloadElevationMap() {
// Write code to map your jsonData to your form elements
$('#dataToSubmit').submit();
}
You could make the form dynamically if you wish. You might be able to update your page to post directly with a submit button.
One final note, you don't need to submit the data as Json. If you have
{
"param1": "value1",
"param2": "value2",
"param3": {
"param4": "value3"
}
}
then if you just use the format in the form above, it will submit fine - this reference explains how to submit to deep models.

jQuery load txt file .html()

how can I decode the html contents of the .txt file when using the $('myDiv').load('mytxtFile.txt')?
I know: $('<div/>').html(value).text();
In other words, How do I combine these two?
important note: the mytextFile.txt, is the container of some of codes which jenerated with ckeditor, and i want to show the content of this txt file in my html form as a html form.
the codes in my txt file is:
<p>hellohome</p>
and I want to show it as : sss hello home sss
in my html page
tank you for your attantion
If I understand the question correctly you can do this:
$('myDiv').load('mytxtFile.txt', function(text) {
$(this).text(text);
});
I think you're after something like this:
$('<div/>').load('mytextFile.txt', function(textStr) {
var htmlStr = $(this).html(textStr).text();
$(this).html(htmlStr);
}).appendTo('form');
That'll effectively encode the html entities, return a properly formed htmlStr, which you can use to set the html() of the element.
Here's a demo fiddle
You can't. load() is designed to pull fragments of HTML directly into the document. If you want to preprocess the data, then load it using $.ajax instead and write your own logic for updating the element content with success.
success: function (data) {
$('myDiv').text(data); // Note: Your selector but not one that is valid for an HTML document
}
You can load the textfile with $.ajax and then add the text with "$('#YOURDIV').text(data)"
Example:
Fiddler: http://jsfiddle.net/ZXMha/
HTML:
JavaScript:
$.ajax({
url: '/echo/html/',
type: "POST",
data: {
html: "<p>Text echoed back to request</p>" + "<script type='text/javascript'>$('target').highlight();<\/script>",
delay: 0
},
success: function(data){
$('#text').text(data);
}
})
Output:
<p>Text echoed back to request</p><script type='text/javascript'>$('target').highlight();</script>
Note: Post is used in this example to simulate an ajax call where html is returned. See http://doc.jsfiddle.net/use/echo.html for Fiddler echo HTML Options.
For your second question: you can simply post the text with .html(data) into your div.
Code:
$.ajax({
url: '/echo/html/',
type: "POST",
data: {
html: "<p>hellohome</p>",
delay: 0
},
success: function(data){
$('#text').html(data);
}
})
Fiddler: http://jsfiddle.net/KWpUC/

Render HTML from JSON object returned from controller to jquery ajax call

In ASP.NET MVC 4 how can I render HTML on load. I am saving some html string encoded in this form in my sql server database as type nvarchar(max).
&lt;li&gt;&lt;li&gt;&lt;img id=&quot;fbPic&quot; src=&quot;http://graph.facebook.com/567818188/picture&quot; style=&quot;display: inline; padding-right: 10px;&quot;&gt;&lt;b&gt;Bernice Zerafa&lt;/b&gt;&lt;/li&gt;&lt;pre class=&quot;word-wrap&quot; style=&quot;margin-left: 10%;&quot;&gt;hellooo&lt;/pre&gt;&lt;/li&gt;
*EDIT:*Please note that the above string is being html unencoded correctly therefore it actually shows like this:
<li><li><img id="fbPic" src="http://graph.facebook.com/567818188/picture" style="display: inline; padding-right: 10px;"><b>Bernice Zerafa</b></li><pre class="word-wrap" style="margin-left: 10%;">helloooo </pre></li>
Now on load of the page I will have a list of those html strings which are all list items with various childnodes to be appended to a unordered list tag. The list is returning ok. But it's only being displayed as is on the page i.e. the actual string is showing and the html is not being rendered.
This is my Controller Action:
public ActionResult LoadPosts(int groupId)
{
var postedText = new List<string>();
IEnumerable<Post> posts;
using (CodeShareEntities conn = new CodeShareEntities())
{
posts = conn.Posts.Where(g => g.GroupId == groupId);
foreach (var post in posts)
{
postedText.Add(post.PostData);
}
}
return Json(new { PostedText = postedText });
}
This is my jQuery Ajax call on load of the page. #posts is an empty <ul> in my html
jQuery.ajax({
type: 'POST',
url: '/Groups/LoadPosts',
data: { groupId: grpid },
success: function (postData) {
$.each(postData, function (index, postText) {
**postText = htmlUnencode(postText);**
$("#posts")[0].innerHTML = postText;
//// what can I do here instead of innerHTML to be
//// able to view the html correctly ?
//// append() and insert() methods in JQuery have the same result
//// I found something called #Html.Raw(Json.Encode()) maybe
//// this is relevant here ? How can I use this correctly ?
});
$('#posts').css('background', 'white');
},
traditional: true
});
Any help would be greatly appreciated!
It seems like your html is double encoded. Try this
$.each(postData, function (index, postText) {
**postText = htmlUnencode(postText);**
$("#posts").append($($("<div/>").html($("<div/>").html(test).text()).text()));
});
Here is a Fiddle sample.
just by looking at your
&lt;li&gt;&lt;li&gt;&lt;img id=&quot;fbPic&quot; src=&quot;http://graph.facebook.com/567818188/picture&quot; style=&quot;display: inline; padding-right: 10px;&quot;&gt;&lt;b&gt;Bernice Zerafa&lt;/b&gt;&lt;/li&gt;&lt;pre class=&quot;word-wrap&quot; style=&quot;margin-left: 10%;&quot;&gt;hellooo&lt;/pre&gt;&lt;/li&gt;
i doubt it going to render correctly it not seems like a valid html and you constantly appending so you might use something like
$("#posts").append(postText);

Categories

Resources