How to use ajax to post Kendo upload files to controller - kendo-ui

When i use ajax to post the form data to controller, i cannot get the files when using Kendo upload. I used IEnumerable but i only can get the date value and the file is null. May i know how to make it work? Thanks.
(I use ajax because i need call the onsuccess event)
//Here is the form control in view
<div class="editForm">
#using (Html.BeginForm("UpdateReportFix", "Defect", FormMethod.Post, new { id = "form" }))
{
#Html.HiddenFor(model => model.DefectFixID)
<div>
#Html.Label("Report Date")
</div>
<div>
#(Html.Kendo().DatePickerFor(model => model.ReportDate)
.Name("ReportDate")
.Value(DateTime.Now).Format("dd/MM/yyyy")
.HtmlAttributes(new { #class = "EditFormField" })
)
#Html.ValidationMessageFor(model => model.ReportDate)
</div>
<div>
#Html.Label("Photos")
<br />
<span class="PhotosMessage">System Allow 2 Pictures</span>
</div>
<div class="k-content">
#(Html.Kendo().Upload()
.Name("files") <-----i cannot get this value in controller
)
</div>
<br />
<div class="col-md-12 tFIx no-padding">
#(Html.Kendo().Button().Name("Cancel").Content("Cancel").SpriteCssClass("k-icon k-i-close"))
#(Html.Kendo().Button().Name("submit").Content("Submit").SpriteCssClass("k-icon k-i-tick"))
</div>
}
//script
$('form').submit(function (e) {
e.preventDefault();
var frm = $('#form');
$.ajax({
url: '#Url.Action("UpdateReportFix")',
type: 'POST',
data: frm.serialize(),
beforeSend: function () {
},
onsuccess: function () { },
success: function (result) { },
error: function () { }
});
});

For "Uploading files using Ajax & Retain model values after Ajax call and Return TempData as JSON" try the following example:
View:
#using (Html.BeginForm("Create", "Issue", FormMethod.Post,
new { id = "frmCreate", enctype = "multipart/form-data" }))
{
<div id="divMessage" class="empty-alert"></div>
#Html.LabelFor(m => m.FileAttachments, new { #class = "editor-label" })
#(Html.Kendo().Upload()
.HtmlAttributes(new { #class = "editor-field" })
.Name("files")
)
}
<script>
$(function () {
//Populate model values of the partialview after form reloaded (in case there is a problem and returns from Controller after Submit)
$('form').submit(function (event) {
event.preventDefault();
showKendoLoading();
var selectedProjectId = $('#ProjectID').val(); /* Get the selected value of dropdownlist */
if (selectedProjectId != 0) {
//var formdata = JSON.stringify(#Model); //For posting uploaded files use as below instead of this
var formdata = new FormData($('#frmCreate').get(0));
$.ajax({
type: "POST",
url: '#Url.Action("Create", "Issue")',
//contentType: "application/json; charset=utf-8", //For posting uploaded files use as below instead of this
data: formdata,
dataType: "json",
processData: false, //For posting uploaded files we add this
contentType: false, //For posting uploaded files we add this
success: function (response) {
if (response.success) {
window.location.href = response.url;
#*window.location.href = '#Url.Action("Completed", "Issue", new { /* params */ })';*#
}
else if (!response.success) {
hideKendoLoading();
//Scroll top of the page and div over a period of one second (1,000 milliseconds = 1 second).
$('html, body').animate({ scrollTop: (0) }, 1000);
$('#popupDiv').animate({ scrollTop: (0) }, 1000);
var errorMsg = response.message;
$('#divMessage').html(errorMsg).attr('class', 'alert alert-danger fade in');
$('#divMessage').show();
}
else {
var errorMsg = null;
$('#divMessage').html(errorMsg).attr('class', 'empty-alert');
$('#divMessage').hide();
}
}
});
}
else {
$('#partialPlaceHolder').html(""); //Clear div
}
});
});
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = null)] Model viewModel, IEnumerable<HttpPostedFileBase> files)
{
//...
return Json(new { success = false, message = "Max. file size is 10MB" }, JsonRequestBehavior.AllowGet);
}

Related

MVC Controller receiving null values from ajax

I'm trying to send an Ajax post to mvc controller contains two parameters.
First parameter: serialized model (Folder)
Second parameter: Array (Periods)
The problem is the controller received null values in the first parameter:
Javascript code :
var data = JSON.stringify({
Folder: $('#Folder').serialize(),
Periods: periodsArr
});
function save(data) {
return $.ajax({
type: 'POST',
//cache: false,
contentType: 'application/json', //Without folder not empty and period is empty
//traditional: true,
//dataType: "json",
url: '#Url.Action("AddOrEditFolder", "Folder")',
data: data,
success: function (result) {
alert(result);
location.reload();
},
error: function () {
alert("Error!" + Error);
}
});
}
Html code:
<div class="card-body">
#using (Html.BeginForm(null, null, new { #id = string.Empty }, FormMethod.Post, new { #id = "Folder" }))
{
#Html.HiddenFor(model => model.FolderID)
<div class="row">
<label for="FirstNameAR" class="col-sm-2 control-label">الإسم الشخصي</label>
<div class="col-sm-4">
#Html.EditorFor(model => model.Trainee.FirstNameAR, new { htmlAttributes = new { #id= "FirstNameAr", #class = "form-control" } })
</div>
<label for="FirstNameFR" class="col-sm-2 control-label">الإسم العائلي</label>
<div class="col-sm-4">
#Html.EditorFor(model => model.Trainee.FirstNameFR, new { htmlAttributes = new { #id = "FirstNameFr", #class = "form-control" } })
</div>
</div> <br />
Controller code:
[HttpPost]
//[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrEditFolder(Folder Folder, Period[] Periods)
{
//Folder Folder = JsonConvert.DeserializeObject<Folder>(Obj);
using (InternshipsEntities dbContext = new InternshipsEntities())
{
//Some code here
}
}
How can I solve that problem ?
Use below code to create data object to pass in Ajax request.
var Folder = { };
$.each($('#Folder').serializeArray(), function() {
Folder[this.name] = this.value;
});
var data = {
Folder: Folder
Periods: periodsArr
};

Upload images via adjusted form and dropzone and codeigniter

Im trying to upload images via dropzone/codeigniter. Unfortantly I dont get the post data to the controller and then to the modal. obviously it's not ajax where i can insert data in order to get it.
Here is part of the form:
<div class="dropzone" id="my-dropzone" name="mainFileUploader">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</div>
Here is the script:
var myDropzone = new Dropzone("#my-dropzone", {
url: "<?=admin_url()?>invoice_items/upload_image",
data: this,
method: "post",
addRemoveLinks:true,
acceptedFiles: '.jpg,.jpeg,.JPEG,.JPG,.png,.PNG',
init: function () {
this.on("addedfile", function (file) {
console.log(file);
});
}
});
Here is the controller
public function upload_image(){
if ($this->input->post()) {
$this->invoice_items_model->add_image($this->input->post());
}
}
Here is the modal
public function add_image($data){
$dat = array(
'rel_name' => $data['name'],
'rel_type' => 'cms_items',
'dateadded' => date('Y-m-d H:i:s')
);
$this->db->insert('tblfiles', $dat);
}
For the one that need an answer:
var myDropzone = new Dropzone("#my-dropzone", {
url: "<?=admin_url()?>invoice_items/upload_image",
files: this,
method: "post",
addRemoveLinks:true,
acceptedFiles: '.jpg,.jpeg,.JPEG,.JPG,.png,.PNG',
init: function (data) {
this.on("sucess",function(file, xhr, formData){
});
},
dictDefaultMessage: "<?=_l('drop_files_here_to_upload')?>",
dictRemoveFile : "<?=_l('remove_file')?>"
});

How to get data from controller to view using ajax request - asp.net mvc 4

I am trying to get data from controller to view using ajax but not successfull. Following is my code this is working fine but not getting data. Please help and correct me if i missed something in my code.
Following is my code.
#model MvcAppLearn.Models.Student
<!DOCTYPE html>
<html lang="en">
<head>
<title>This is tile</title>
</head>
<body>
#using (Html.BeginForm("Index", "popup", FormMethod.Get, new { id = "myform" }))
{
<p>
Find by name: #Html.TextBox("SearchString")
<button id="model-opener">Open dialog</button>
</p>
<div id="dialog-model" title="This is title">
<p>
#Html.TextBoxFor(item => item.FirstName, new { id = "ffirst" })<br />
#Html.TextBoxFor(item => item.LastName, new { id = "llast" })<br />
</p>
</div>
}
</body>
</html>
#section script
{
<script>
$(function () {
$("#dialog-model").dialog({
autoOpen: false,
height: 300,
width: 340,
model: true,
show: {
effect: "shake",
duration: 100
},
});
$("#model-opener").click(function (e) {
e.preventDefault();
var txtFirstName = $('#ffirst');
var txtLastName = $('#llast');
var txtSearch = $('#SearchString');
$.ajax({
url: '/popup/Index',
type: 'GET',
data: {
StudentId: txtSearch.val()
},
success: function (data) {
txtFirstName.val(data.FirstName); //HERE IS THE PROBLEM IN GETTING VALUE
txtLastName.val(data.LastName); //HERE IS THE PROBLEM IN GETTING VALUE
$("#dialog-model").dialog("open");
},
error: function () {
alert("Oh noes");
}
});
});
});
</script>
}
Below is my controller
public ActionResult Index(int? StudentId)
{
if (StudentId == null)
{
StudentId = 2;
return View();
}
using (var db = new StdContext())
{
Student std = new Student();
std = db.Students.Where(m => m.StudentId == StudentId).Single();
return View(std);
}
}
You're not returning data, you're returning a view:
return View(std);
If you just want to return the data of the Student object to be consumed by JavaScript code then you probably just want to return it as JSON data:
return Json(std);

How to do Jquery ajax post to controller mvc

I just can't figure out what I am not doing right,From a viewmodel,I try to grab from user {**Tousername and messagebody},#ToUserName** is correctly sent while #Body is null in controller when I debug .I have the following Jquery code:
$("#SendMessage").click(function () {
var message = GrabMessage();
var jsonData = JSON.stringify(message, null, 2);
$.ajax({
url: '#Url.Content("~/Message/Compose/")',
type: 'POST',
data: jsonData,
datatype: 'json',
contentType: 'application/json; charset=utf-8',
success: function () {
$('#default_message').append("message sent ");
switchToSentMessagesTab();
},
error: function (request, status, err) {
alert(status);
alert(err);
}
});
return false;
});
function switchToSentMessagesTab() {
$('a[href="#default_message"]').click();
}
function GrabMessage() {
var touser = $("#ToUserName").val();
var text = $("#Body").val();
var result =
{
Body: text,
ToUserName: touser
};
return result;
}
});
And the razer View:
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<div class="editor-label">
#Html.LabelFor(model => model.ToUserName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ToUserName, new { #class ="autocomplete"})
#Html.ValidationMessageFor(model => model.ToUserName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Body)
#Html.ValidationMessageFor(model => model.Body)
</div>
<p>
<input id="SendMessage" type="submit" value="Send" />
</p>
}
and controller Action:
[HttpPost]
public ActionResult Compose(PrivateMessageViewModel m)
{
if (User.Identity.IsAuthenticated )
{
if (ModelState.IsValid)
{
var ToUserName = users.Profiles.First(x => x.UserName == m.ToUserName);
PrivateMessage message = new PrivateMessage
{
//do some stuff here:
};
db.SendMessage(message);
return RedirectToAction(//Some view here...)
}
}
return PartialView(m);
}

Reset tinyMCE box after submit

i have the follow MVC View
#model Site.SupportItems.SiteAditionalInformation
#using Site.Helpers.Extenders;
#{
Response.CacheControl = "no-cache";
}
<div>
#using (Html.BeginForm("SaveSiteAdditionalInformation", "Support", FormMethod.Post, new { #Id = "frmSiteInformation" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Site Aditional Information</legend>
<div class="site-PO-footer-outline-left-comment">
<div class="site-item-outline">
<div class="site-label-left ui-corner-all">
#Html.LabelFor(model => model.Office)
</div>
<div class="site-detail">
#Html.DropDownListFor(x => x.Office, Model.Offices.ToSelectList("ValueSelected", "DisplayValueSelected", Model.Office))
#Html.ValidationMessageFor(model => model.Office)
</div>
</div>
<div class="site-item-outline">
<div class="site-label-left ui-corner-all">
#Html.LabelFor(model => model.AdditionalInformation)
</div>
<div class="site-detail">
#Html.TextAreaFor(model => model.AdditionalInformation, new { #Class = "ui-site-rtb" })
#Html.ValidationMessageFor(model => model.AdditionalInformation)
</div>
</div>
</div>
<p>
<input type="submit" value="Save" id="btnSubmit" />
</p>
</fieldset>
}
<script type="text/javascript">
$(function ()
{
var thisTab = $(Globals.ActiveTabId());
var previousSelectedOffice;
$('#Office', thisTab).click(function ()
{
previousSelectedOffice = $('#Office', thisTab).val();
}).change(function (e)
{
var setNewContent = function ()
{
$('#loading-Panel').Loading('show');
$.ajax('#Url.Action("GetSiteSpecificText")', {
data: { Office: $('#Office', thisTab).val(),
rnd: Math.random() * 10000
},
cached: false,
success: function (response)
{
if (response != null)
{
$('#AdditionalInformation', thisTab).html(response);
}
else
$('#AdditionalInformation', thisTab).html('');
$('#loading-Panel').Loading('hide');
}
});
};
if (tinyMCE.activeEditor.isDirty())
{
$('<div/>').text('The Text has changed for the Additional Information. Would you like to save?').dialog({
title: 'Text has Changed',
buttons: {
'Ok': function ()
{
$('#loading-Panel').Loading('show');
var beforeSave = $('#Office', thisTab).val();
$('#Office', thisTab).val(previousSelectedOffice);
$('#frmSiteInformation', thisTab).trigger('submit');
$('#Office', thisTab).val(beforeSave);
setNewContent();
$(this).dialog('close');
},
'Cancel': function ()
{
$(this).dialog('close');
$('#Office', thisTab).val(previousSelectedOffice);
}
}
});
}
else
{
setNewContent();
}
});
$('#frmSiteInformation', thisTab).submit(function ()
{
tinyMCE.triggerSave();
var data = $('#frmSiteInformation', thisTab).serializeObject();
$('#loading-Panel').Loading('show');
$.ajax($(this).attr('action'), {
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
success: function (data)
{
if (data.SaveResult)
$('<div/>').text('Save Successful for' + $('#Office option:selected', thisTab).text())
.dialog({
title: 'Save Successful',
buttons: {
'Ok': function ()
{
$(this).dialog('close');
}
}
});
$('#loading-Panel').Loading('hide');
}
});
return false;
});
});
</script>
</div>
and while most of it is doing what i expect if i change the dropdown i want to clear the RTB back to nothing (or the response value if there is one from the DB)
while this is working if i change the dropdown again the tinyMCE.activeEditor.isDirty() is always coming back as true when i believe it should be false.
i have tried tinymce.execCommand('mceToggleEditor',false,'AdditionalInformation');
but this only reloads the first RTB
and also tinymce.execCommand('mceRemoveEditor',false,'AdditionalInformation');
which causes an error.
if anyone could point me in the right direction i would really appreciate it.
thanks.
Edit I have solved the problem i am having using the mceRemoveEditor command
the function call for setNewContent is as follows
var setNewContent = function ()
{
$('#loading-Panel').Loading('show');
$.ajax('#Url.Action("GetSiteSpecificText")', {
data: { Office: $('#Office', thisTab).val(),
rnd: Math.random() * 10000
},
cached: false,
success: function (response)
{
tinymce.execCommand('mceRemoveEditor', false, 'AdditionalInformation');
if (response != null)
{
$('#AdditionalInformation', thisTab).html(response);
}
else
$('#AdditionalInformation', thisTab).html('');
tinymce.execCommand('mceAddControl', false, 'AdditionalInformation');
$('#loading-Panel').Loading('hide');
}
});
};
Thanks for the help.

Resources