Data not binding on edit - c#

I'm trying to implement the CKEditor for a blog. I've got the Create Blog working fine, but for some reason the Edit Blog page does not display content which already exists.
If I remove the CKEditor.replace script, then the normal EditorFor displays fine. See images below.
I've read lots of posts, as well as the CKEditor documentation, and what I'm doing is supposedly correct.
Is there a trick to get the pre-existing data to show in the CKEDITOR content area?
Here's the JS to add the CKEDITOR
<script>CKEDITOR.replace("MainContent")</script>
Here's the HTML.
<div class="col-md-10">
#Html.EditorFor(model => model.Content,
new { htmlAttributes =
new { #id = "MainContent", #class = "form-control" } })
</div>
When the CKEDITOR.replace is used, it looks like this... no data shows in the Content area.
When the CKEDITOR.replace is removed, it looks like this, the content displays correctly

ok, I'm not sure why it does not work out of the box the way it is described, but I added a bit of JavaScript and now it's working. I'd still love input on why it does not work as described.
$.ajax({
url: 'Blog/Edit',
type: 'POST',
data: JSON.stringify(Blog),
contentType: 'application/json;charset=utf-8',
success: function (data) {
if (data.success == true) {
window.location.href = "../Blog";
}
else if (data.success == false) {
alert("Error occured..!!")
}
},
error: function () {
alert("Error occured..!!");
},
});

Related

Converting string back to HTML

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!

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

Appended items not showing when using multi-select listbox

The appended items work perfectly when not including the 2nd Script(which is what gives the listbox a sleek looking listbox with checkboxes in it) - but when I do include it, then it doesnt append the items.
Is there any reason why ?
JQuery:
$("#ddlistcategory").change(function () {
var catItem = $("#ddlistcategory").val();
$("#ddlistaccountitems").empty();
$.ajax({
url: '#Url.Action("GetCategories", "Account")',
dataType: "json",
type: "Post",
data: { "i": catItem },
success: function (data) {
$.each(data, function (key, val) {
//alert(key + " " + val);
$("#ddlistaccountitems").append('<option id="' + key + '">' + val + '</option>');
})
}
});
});
$('#ddlistaccountitems').multiselect({
includeSelectAllOption: false,
allSelectedText: 'No option left ...',
enableFiltering: true,
filterPlaceholder: 'Search for something...'
});
View:
<div class="form-group form-group-sm">
#Html.Label("Items", new { #class = "control-label" })
#Html.ListBoxFor(x => x.SelectedAccountItems, Model.UserItems, new { #class = "form-control", #id = "ddlistaccountitems", #multiple = "multiple" })
</div>
You are calling multiselect outside of your ajax method which is populating the element with the options. As a result you will be initializing it before the ajax has finished, so the issue is most likely that the initialization does not yet have the options to build from.
To fix this, move the initialization into the success method so it will execute after the ajax has finished and all the data that it needs has been created.
Your Ajax call will work asynchronously. That is, the .multiselect will execute before the options appended. .multiselect will hide your actual select and replace it with custom html. So you have to fill it before .multiselect execution. add
async: false
in Ajax call or call
$('#ddlistaccountitems').multiselect()
inside that success function.

Sending HttpPostedFileBase field using JQuery ajax form.serialize() in MVC

I'm working on an MVC project.I have a form Like below:
<div id="horizontal-form">
#using (Html.BeginForm("Send", "Ticket", FormMethod.Post, new
{
#class = "form-horizontal",
role = "form",
id = "form_send_ticket",
enctype = "multipart/form-data"
}))
{
#**** I have about 20 filed's of other types here ****#
......
#**** Image file ****#
#Html.TextBoxFor(x => x.Image, new { type = "file" })
<div>
<button type="button" class="btn btn-success" id="send_ticket">Insert</button>
</div>
}
</div>
My ViewModel:
public class SendViewModel
{
//I have about 20 filed's of other types here
.....
//Image file
public HttpPostedFileBase Image { get; set; }
}
My JQuery ajax:
$("#send_ticket").click(function () {
var form = $("#form_send_ticket");
$.ajax({
type: "POST",
url: '#Url.Action("Send", "Ticket")',
data: form.serialize(),
contentType: "multipart/form-data",
success: function (data) {
//do something
},
error: function (e) {
//do something
}
});
})
My Controller Action is like this:
[HttpPost]
public ActionResult Send(SendViewModel ticket)
{
//Do something
return Json(new { });
}
Before this situation I faced,I mean in other projects,mostly I had about 3 to 8 field's including image file an some other types and I append them one by one to FormData(because of that Image file) then send them through ajax request and it was no matter for me,but now I have about 22 field's and it's a little though to do this.so I decided to serialize the form and send it through ajax request and it's working good form all filed's except Image which I make it the type HttpPostedFileBase in ViewModel. Any Idea how to send this field with form using data: form.serialize()?
appreciate your help :)
Update:
let me clear some point's:
1-I don't want FormData to send through ajax and I want to send using form.serialize().
2-Don't want to use ready file plugins.
3-I don't mean just one image field ,I mean whole the form with 23 field's.
You cannot post/upload a file using jQuery Ajax, unless you are going to use FormData or some plugins which internally use iFrame implementations.

Validation on Ajax loaded form - presenting back the validation summary

I am trying to validate a submitted form that is loaded in isolation to the rest of the page. I use validation all the time with my normal non ajax loaded content. I go on this principle:
Submit the form
pass the request from my controller to my service
Validate the object in the service
pass back to the controller a bool depending on the validation state
Present the original form back with validation summary if there are validation errors
Present a success page if there are no validation errors
That works fine on non-ajax content.
Now lets consider my issue. I have this kind of structure:
<div id="mainContent">
<div id="leftContent"></div>
<div id="rightContent"></div>
</div>
<script>
$.ajax({
url: baseUrl + "home/newApplicationForm/",
type: "GET",
success: function (data) {
$("#rightContent").html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error displaying content");
}
});
</script>
This puts my blank application form on the right hand side of the page.. everything else on the page is left unchanged by that ajax.
So home/newapplicationform now displays the form that is wrapped with:
#model homelessRentals.Model.Application
#{
AjaxOptions options = new AjaxOptions{
HttpMethod = "Post",
UpdateTargetId = "AddApplication"
};
}
#using (Ajax.BeginForm(options)) {
#Html.ValidationSummary(true)
<div class="editor-field">
#Html.EditorFor(model => model.YourName)
#Html.ValidationMessageFor(model => model.YourName)
</div>
<input type="submit" value="Add Application" id="saveMe"/>
}
This form now pings back to my controller:
[HttpPost]
public ActionResult AddApplication(Application app)
{
bool validated = _service.AddApplication(app);
if(validated)
{
return PartialView("SuccessApp");
}
return PartialView(app);
}
This will either return me to my form with validation errors shown or route me to my success page. This works to the extent that the logic is right, BUT I get presented the partial view in replacement of the whole page - it is not presented back in the 'rightContent' div.
I have tried submitting the form and catching the submission in jquery, then running something like this but I get the same behaviour:
$.ajax({
url: baseUrl + "home/AddApplication/",
data: "{'app':" + JSON.stringify(newApp) + "}",
type: "POST",
success: function (data) {
$("#rightContent").html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error displaying content");
}
});
Can anyone help me with a better way to achieve this validation?
Many thanks
The UpdateTargetId is incorrect, this needs to point to rightContent rather than AddApplication.
#{
AjaxOptions options = new AjaxOptions{
HttpMethod = "Post",
UpdateTargetId = "rightContent"
};
There is no dom element with the id of AddApplication.

Categories

Resources