asp.net mvc Ajax submit form with fileinput in jquery plugin - asp.net-mvc

I'm having problems with an form.
I need to submit a form with ajax with fileinput in the form. In this form, I use the plugin with fileinput. This is the website
Here is my code:
<link href="~/Content/Plugin/bootstrap-fileinput-master/css/fileinput.min.css" rel="stylesheet" />
<script src="~/Content/Plugin/bootstrap-fileinput-master/js/fileinput.min.js"></script>
<script src="~/Content/Plugin/bootstrap-fileinput-master/js/fileinput_locale_zh.js"></script>
#using (Ajax.BeginForm(null, null, new AjaxOptions(){
HttpMethod = "post",Url = Url.Action("Upload", "WorkItem"),
InsertionMode = InsertionMode.Replace, LoadingElementDuration = 2000,
OnSuccess = "completed" },
new { role = "form", enctype = "multipart/form-data" }))
{
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">TITLE</span>
<input type="text" name="Descr" class="form-control" aria-describedby="basic-addon1">
</div>
<div class="m-b-5"></div>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">POINT</span>
<input type="text" name="Point" class="form-control" aria-describedby="basic-addon1">
</div>
<div class="m-b-5"></div>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">DESCR</span>
<input type="text" name="Descr" class="form-control" aria-describedby="basic-addon1">
</div>
<div class="m-b-5"></div>
<input id="file-0a" name="file" class="file" type="file" data-min-file-count="1">
<br />
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
}
When I click the submit button, no file can be accepted. What is going wrong?

As #Stepher Muecke told #Ajax.BeginForm can not be used to post Files.
I dont have a idea about plugin.I use the following method:
$("#btnUploadExcel").click(function () {
if ($("#newuploadexcel").val() == '') {
notie.alert(2, "Please Select Any File", 2);
}
else {
if (window.FormData!= undefined) {
var fileUpload = $("#newuploadexcel").get(0);
var files = fileUpload.files;
// Create FormData object
var fileData = new FormData();
// Looping over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
// Adding one more key to FormData object
// fileData.append('contentId', contentId); commented as now supplierId is passed in the excel itself
$.ajax({
url: '/BulkStock/UploadExcel',
data: fileData,
type: "POST",
async: true,
dataType: 'json',
contentType: false,
processData: false,
success: function (result) {
var data = result.message;
//1=Failure, No excel
//2= Failue, with excel
//3=success, no excel
if (result.errmsg == '3') {
notie.alert(1, data, 6);
}
else if (result.errmsg == '1') {
notie.alert(3, data, 6);
}
else {
window.location = result.link;
notie.alert(3, data, 10);
}
},
error: function (response) {
console.log(response.responseText);
},
failure: function (response) {
console.log(response.responseText);
}
});
$("#newUpload").modal('hide');
} else {
notie.alert(3, "FormData is not supported.", 3);
}
}
});
And my controller to get file is:
public JsonResult UploadExcel()
{
string filePath = String.Empty;
string fileName = string.Empty;
if (Request.Files.Count > 0)
{
// Get all files from Request object
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFileBase file = files[i];
fileName = file.FileName;
string extension = System.IO.Path.GetExtension(fileName);
if (extension.Equals(".xls") || extension.Equals(".xlsx"))
{
var now = DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture);
string my3DigitRandomNumber = now.Substring(now.Length - 7, 3);
fileName = (file.FileName.Replace(extension, "")) + (my3DigitRandomNumber + extension);
filePath = string.Format("{0}/{1}", Server.MapPath("~/excelfiles"), fileName);
file.SaveAs(filePath);
}
}
}
}
Create a folder with the name "excelfiles" in your solution

Related

List<IFormFile> files gets nothing from dropzone post mvc

I'm trying to send images from dropzone to my controller mvc project by httpPost
The forms are calling correctly the IActionResult but the files count are always 0
When the forms load I get
but I'm already giving a URL. Don't know what's the error.
Here is my cshtml script of dropzone config
#section Scripts
{
<link rel="stylesheet" href="~/css/basic.css" />
<link rel="stylesheet" href="~/css/dropzone.css" />
<script type="text/javascript" src="~/js/dropzone.js"></script>
<script type="text/javascript" src="~/js/dropzone-amd-module.js"></script>
<script>
Dropzone.autoDiscover = false;
$(document).ready(function () {
$('#myDropzone').dropzone({
url:"/Aprovacoes/SaveUploadedFile",
method: "post",
//parameter name value
paramName: function () { "files" },
//clickable div id
clickable: '#previews',
//preview files container Id
previewsContainer: "#previews",
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
// url:"/", // url here to save file
maxFilesize: 100,//max file size in MB,
addRemoveLinks: true,
dictResponseError: 'Server not Configured',
acceptedFiles: ".png,.jpg,.gif,.bmp,.jpeg,.pdf",// use this to restrict file type
init: function () {
var self = this;
// config
self.options.addRemoveLinks = true;
self.options.dictRemoveFile = "Delete";
//New file added
self.on("addedfile", function (file) {
console.log('new file added ', file);
$('.dz-success-mark').hide();
$('.dz-error-mark').hide();
});
// Send file starts
self.on("sending", function (file) {
console.log('upload started', file);
$('.meter').show();
});
// File upload Progress
self.on("totaluploadprogress", function (progress) {
console.log("progress ", progress);
$('.roller').width(progress + '%');
});
self.on("queuecomplete", function (progress) {
$('.meter').delay(999).slideUp(999);
});
// On removing file
self.on("removedfile", function (file) {
console.log(file);
});
$('#Submit').on("click", function (e) {
e.preventDefault();
e.stopPropagation();
// Validate form here if needed
if (self.getQueuedFiles().length > 0) {
self.processQueue();
} else {
self.uploadFiles([]);
$('#myDropzone').submit();
}
});
self.on("successmultiple", function (files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
});
}
});
})
</script>
And here is the form
#using (Html.BeginForm("SaveUploadedFile", "Aprovacoes", FormMethod.Post, new { #name = "myDropzone", id = "myDropzone", #enctype = "multipart/form-data" }))
{
<br />
<div>
<div id="previews" class="dz-default dz-message box__input dropzone">
<div style="text-align:center">
<i class="fa fa-cloud-upload" style="font-size:23px;position:relative;top:4px;"></i> <span style="margin-left:20px">Drop files to attach or browse</span>
</div>
</div>
</div>
<br />
<div>
<input type="submit" id="Submit" name="Submit" class="btn btn-success m-t-5" value="Submit" />
</div>
}
My controller httpPost method
[HttpPost]
public IActionResult SaveUploadedFile(List<IFormFile> files)
{
//do stuff
}
always come 0
This is my working solution:
View Part
#using (Ajax.BeginForm("YourAction", "YourController", FormMethod.Post, new AjaxOptions { HttpMethod = "POST", OnBegin = "OnBegin", OnSuccess = "OnSuccess", OnFailure = "OnFailure" }, new { #id = "ajaxForm", #enctype = "multipart/form-data" }))
{
<div class="card">
<div class="card-body">
#Html.AntiForgeryToken()
<div class="col-md-12 dropzone">
<div class="dropzone-previews" id="dropzonePreview">
<i class="icon-file-upload icon-5x absolute-center text-muted"></i>
</div>
</div>
</div>
<div class="row form-group mt-3">
<div class="col-md-12">
<input class="btn btn-inverse btn-primary" id="btnSubmit" name="inputSubmit" type="submit" value="Save" />
</div>
</div>
</div>
</div>
}
Script Part
Dropzone.autoDiscover = false;
var options = {
paramName: "PhotoFiles",
addRemoveLinks: true,
autoDiscover: false,
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 5,
thumbnailWidth: 250,
thumbnailHeight: 250,
dictRemoveFile: 'Delete',
previewsContainer: '#dropzonePreview',
clickable: '.dropzone',
acceptedFiles: ".jpeg,.jpg,.png",
};
var dropZone = new Dropzone("form#ajaxForm", options);
dropZone.element.querySelector("input[type=submit]").addEventListener("click", function (e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
// if dropzone has file process them, if not send empty array
if (dropZone.getQueuedFiles().length > 0) {
dropZone.processQueue();
} else {
$("#ajaxForm").submit();
}
});
dropZone.on("successmultiple", function (files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
OnSuccess(response);
});
dropZone.on("errormultiple", function (files, response) {
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
OnFailure(response);
});
Controller Part
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult InsertPhotos()
{
if (Request.Files.Count > 0)
{
for (int i = 0; i < Request.Files.Count; i++)
{
//process files
}
}
//return some result
return Json(result, JsonRequestBehavior.AllowGet);
}
Hope it helps.

MVC POP Up and PostBack

I have a MVC c#, signalR project where Agent follow below steps in Application
Login To application. Once login success application hides Login div panel & displays list of campaign & telephony buttons
Application displays list of campaigns agent is assigned to
Application displays button in front of each campaign to set Ready / Not Ready in campaign. In this case it is RestAPI & Telemarketing
If agent need to set himself not ready in campaign it opens popup window with list not ready reasons.
Issue is :
When Agent select reason and submit it application post back it lost view and reset to login window.
Controller action after submit of breakreason in PopUp window:
public ActionResult SetBreak(breakReasonModel form)
{
string tok=form.accessToken;
string cmp = form.campaign;
string selreason = "";
for (int i=0;i < form.arrReasons.Length;i++)
{
selreason = form.arrReasons[i];
}
SetBreak obj = new SetBreak();
System.Collections.Generic.List<ISCampaigns> IScampaignNames = new System.Collections.Generic.List<ISCampaigns>();
IScampaignNames = obj.setNotReadyInCampaign(tok, cmp, selreason);
return RedirectToAction("Index");
}
PopUp Partial View :
#using Altitude.IntegrationServer.RestApiWebApp.Models
#model Altitude.IntegrationServer.RestApiWebApp.Models.breakReasonModel
<div id="divBreakReasons">
#using (Html.BeginForm("SetBreak", "Home"))
{
#Html.ListBoxFor(m => m.arrReasons, Model.reasonsMultiSelectList, new { #class = "form-control" })
#Html.TextBoxFor(model => model.accessToken, new { id = "txtaccessToken" })
#Html.TextBoxFor(model => model.campaign, new { id = "txtcampaign" })
<br />
<button id="btn" type="submit" class="btn btn-block bg-primary" value="Submit" >Submit</button>
<br />
}
</div>
Index.chtml
<div class="row">
<div class="col-md-4 table-responsive" id="telButtons">
<table id="tblTelephony" class="table">
--Telephony Buttons
</tbody>
</table>
</div>
</div>
<div class="row">
<div class="col-md-4 table-responsive">
<p id="demo"></p> // Campaign table with Ready/Not Ready buttons
</div>
</div>
//ajax call to open popup
<div id="dialog" style="display: none"></div>
<script type="text/javascript">
function getBreak(nrReason) {
$("#dialog").dialog({
autoOpen: false,
modal: true,
});
$.ajax({
type: "POST",
url: "#Url.Action("popupBreak","Home")",
data: '{breakReason : "' + dataToSend + '",accessToken : "' +acc+ '",campaign : "' + cmp + '"}',
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (response) {
$('#dialog').html(response);
$('#dialog').dialog('open');
console.log(response);
},
failure: function (response) {
},
error: function (response) {
}
});
}
</script>
It does exactly what you coded. If you need to return result to current view you should use ajax call that will return action result.
example
#using (Ajax.BeginForm("Action", "Controller", FormMethod.Post, new AjaxOptions() { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "YourTargetForResult" }, new { #id = "ajaxForm" }))
You must reference jquery.unobtrusive-ajax.js to receive postback in current view.
Example based on your comment:
<input type="hidden" id="hdnResponseMessage" /> // add dom object where response hits
#using (Ajax.BeginForm("SetBreak", "YourControllerName", FormMethod.Post, new AjaxOptions() { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "hdnResponseMessage" }, new { #id = "form" }))
{
#Html.ListBoxFor(m => m.arrReasons, Model.reasonsMultiSelectList, new { #class = "form-control" })
#Html.TextBoxFor(model => model.accessToken, new { id = "txtaccessToken" })
#Html.TextBoxFor(model => model.campaign, new { id = "txtcampaign" })
<br />
<button id="btn" type="submit" class="btn btn-block bg-primary" value="Submit" >Submit</button>
<br />
}
Conroller:
[HttpPost]
public JsonResult SetBreak(breakReasonModel form)
{
string tok=form.accessToken;
string cmp = form.campaign;
string selreason = "";
for (int i=0;i < form.arrReasons.Length;i++)
{
selreason = form.arrReasons[i];
}
SetBreak obj = new SetBreak();
System.Collections.Generic.List<ISCampaigns> IScampaignNames = new System.Collections.Generic.List<ISCampaigns>();
IScampaignNames = obj.setNotReadyInCampaign(tok, cmp, selreason);
return Json("SetBreak");
}
jQuery set listener in document ready:
// add dom object listener
$('#hdnResponseMessage').bind('DOMNodeInserted', function () {
var txt = $('#hdnResponseMessage').text();
if (txt == 'SetBreak')
{
//do your stuff here;
}
});

MVC Full Calendar doesn´t show the events

I am implementing a calendar and I have encountered some difficulties because I am learning JavaScript alone and I have not mastered yet.
My problem is this: I can create the event and save it in the database, but the event and the color of it ... do not appear on the calendar ... can someone find out the solution or where is the problem?
If possible ... to create events ... being the color of this event always in random color?
View
<div id="calender"></div>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><span id="eventTitle"></span></h4>
</div>
<div class="modal-body">
<button id="btnDelete" class="btn btn-default btn-sm pull-right">
<span class="glyphicon glyphicon-remove"></span> Remover
</button>
<button id="btnEdit" class="btn btn-default btn-sm pull-right" style="margin-right:5px;">
<span class="glyphicon glyphicon-pencil"></span> Editar
</button>
<p id="pDetails"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
</div>
</div>
</div>
</div>
<div id="myModalSave" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Salvar Evento</h4>
</div>
<div class="modal-body">
<form class="col-md-12 form-horizontal">
<input type="hidden" id="hdID_Reserva" value="0" />
<div class="form-group">
<label>Cliente</label>
<input name="Nome" class="form-control" type="text" placeholder="Introduza o Nome" id="txtCliente">
<input type="hidden" id="txtID_Cliente" name="ID_Cliente" />
</div>
<div class="form-group">
<label>Data de Entrada</label>
<div class="input-group date" id="dtp1">
<input type="text" id="txtDataEntrada" name="DataEntrada" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<label>Data de Saida</label>
<div class="input-group date" id="dtp1">
<input type="text" id="txtDataSaida" name="DataSaida" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<label>Número Quarto</label>
#Html.DropDownList("ID_Quarto", null, "Selecione o Quarto", htmlAttributes: new { #class = "form-control" })
</div>
<div class="form-group">
<label>Número Pessoas</label>
<input id="txtNumeroPessoas" name="NumeroPessoas" class="form-control" />
</div>
<div class="form-group">
<label>Número Noites</label>
<input id="txtNumeroNoites" name="NumeroNoites" class="form-control" />
</div>
<div class="form-group">
<label>Preço</label>
<input id="txtPreço" name="Preço" class="form-control" />
</div>
<div class="form-group">
<label>Observações</label>
<input id="txtObservaçoes" name="Observaçoes" class="form-control" />
</div>
<button type="button" id="btnSave" class="btn btn-success">Salvar</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
</form>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="~/AdminLTE/plugins/fullcalendar-3.9.0/fullcalendar.min.css" rel="stylesheet" />
<link href="~/AdminLTE/plugins/fullcalendar-3.9.0/fullcalendar.print.min.css" rel="stylesheet" media="print" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css" rel="stylesheet" />
#section Scripts{
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="~/AdminLTE/plugins/fullcalendar-3.9.0/fullcalendar.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<script>
$(document).ready(function () {
var events = [];
var selectedEvent = null;
FetchEventAndRenderCalendar();
function FetchEventAndRenderCalendar() {
events = [];
$.ajax({
type: "GET",
url: "/CalendárioReservas/GetEvents",
success: function (data) {
$.each(data, function (i, v) {
events.push({
eventID: v.ID_Reserva,
clienteID: v.ID_Cliente,
quartoID: v.ID_Quarto,
inicio: moment(v.DataEntrada),
fim: v.DataSaida != null ? moment(v.DataSaida) : null,
noites: v.NumeroNoites,
pessoas: v.NumeroPessoas,
preço: v.Preço,
obs: v.Observaçoes
});
})
GenerateCalender(events);
},
error: function (error) {
alert('failed');
}
})
}
function GenerateCalender(events) {
$('#calender').fullCalendar('destroy');
$('#calender').fullCalendar({
contentHeight: 400,
defaultDate: new Date(),
timeFormat: 'h(:mm)a',
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay,agenda'
},
eventLimit: true,
eventColor: '#378006',
events: events,
eventClick: function (calEvent, jsEvent, view) {
selectedEvent = calEvent;
$('#myModal #eventTitle').text(calEvent.clienteID);
var $quartoID = $('<div/>');
$quartoID.append($('<p/>').html('<b>DataEntrada:</b>' + calEvent.inicio.format("DD-MMM-YYYY HH:mm a")));
if (calEvent.fim != null) {
$quartoID.append($('<p/>').html('<b>DataSaida:</b>' + calEvent.fim.format("DD-MMM-YYYY HH:mm a")));
}
$quartoID.append($('<p/>').html('<b>ID_Quarto:</b>' + calEvent.quartoID));
$('#myModal #pDetails').empty().html($quartoID);
$('#myModal').modal();
},
selectable: true,
select: function (inicio, fim) {
selectedEvent = {
eventID: 0,
clienteID: '',
quartoID: '',
inicio: inicio,
fim: fim,
pessoas: '',
noites: '',
preço: '',
obs: ''
};
openAddEditForm();
$('#calendar').fullCalendar('unselect');
},
editable: true,
eventDrop: function (event) {
var data = {
ID_Reserva: event.eventID,
ID_Cliente: event.clienteID,
DataEntrada: event.inicio.format('DD/MM/YYYY HH:mm A'),
DataSaida: event.fim != null ? event.fim.format('DD/MM/YYYY HH:mm A') : null,
ID_Quarto: event.quartoID,
NumeroNoites: event.noites,
NumeroPessoas: event.pessoas,
Preço: event.preço,
Observaçoes: event.obs
};
SaveEvent(data);
}
})
}
$('#btnEdit').click(function () {
//Open modal dialog for edit event
openAddEditForm();
})
$('#btnDelete').click(function () {
if (selectedEvent != null && confirm('Are you sure?')) {
$.ajax({
type: "POST",
url: '/CalendárioReservas/DeleteEvent',
data: { 'eventID': selectedEvent.eventID },
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModal').modal('hide');
}
},
error: function () {
alert('Failed');
}
})
}
})
$('#dtp1,#dtp2').datetimepicker({
format: 'DD/MM/YYYY HH:mm A'
});
//$('#chkDiaTodo').change(function () {
// if ($(this).is(':checked')) {
// $('#divDataFim').hide();
// }
// else {
// $('#divDataFim').show();
// }
//});
function openAddEditForm() {
if (selectedEvent != null) {
$('#hdID_Reserva').val(selectedEvent.eventID);
$('#txtID_Cliente').val(selectedEvent.clienteID);
$('#txtDataEntrada').val(selectedEvent.inicio.format('DD/MM/YYYY HH:mm A'));
//$('#chkDiaTodo').prop("checked", selectedEvent.allDay || false);
//$('#chkDiaTodo').change();
$('#txtDataSaida').val(selectedEvent.fim != null ? selectedEvent.fim.format('DD/MM/YYYY HH:mm A') : '');
$('#ID_Quarto').val(selectedEvent.quartoID);
$('#txtNumeroNoites').val(selectedEvent.noites);
$('#txtNumeroPessoas').val(selectedEvent.pessoas);
$('#txtPreço').val(selectedEvent.preço);
$('#txtObservaçoes').val(selectedEvent.obs);
}
$('#myModal').modal('hide');
$('#myModalSave').modal();
}
$('#btnSave').click(function () {
//Validation/
if ($('#txtID_Cliente').val().trim() == "") {
alert('Introduza um Título');
return;
}
if ($('#txtDataEntrada').val().trim() == "") {
alert('Introduza uma Data de Início');
return;
}
//if ($('#chkDiaTodo').is(':checked') == false && $('#txtDataFim').val().trim() == "") {
// alert('Introduza uma Data de Fim');
// return;
//}
else {
var startDate = moment($('#txtDataEntrada').val(), "DD/MM/YYYY HH:mm A").toDate();
var endDate = moment($('#txtDataSaida').val(), "DD/MM/YYYY HH:mm A").toDate();
if (startDate > endDate) {
alert('Data de Fim Inválida');
return;
}
}
var data = {
ID_Reserva: $('#hdID_Reserva').val(),
ID_Cliente: $('#txtID_Cliente').val().trim(),
DataEntrada: $('#txtDataEntrada').val().trim(),
DataSaida: $('#txtDataSaida').val().trim(),
ID_Quarto: $('#ID_Quarto').val(),
NumeroPessoas: $('#txtNumeroPessoas').val(),
NumeroNoites: $('#txtNumeroNoites').val(),
Preço: $('#txtPreço').val(),
Observaçoes: $('#txtObservaçoes').val()
}
SaveEvent(data);
// call function for submit data to the server
})
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '/CalendárioReservas/SaveEvent',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function () {
alert('Failed');
}
})
}
})
</script>
controller
namespace WebApplication.Controllers
{
public class CalendárioReservasController : Controller
{
private HotelEntities db = new HotelEntities();
// GET: CalendárioReservas
public ActionResult Index()
{
ViewBag.ID_Quarto = new SelectList(db.Quarto, "ID_Quarto", "ID_Quarto");
return View();
}
public JsonResult GetEvents()
{
try
{
var events = db.Reserva.Select(p => new
{
ID_Reserva = p.ID_Reserva,
ID_Cliente = p.ID_Cliente,
ID_Quarto = p.ID_Quarto,
DataEntrada = p.DataEntrada,
DataSaida = p.DataSaida,
NumeroNoites = p.NumeroNoites,
NumeroPessoas = p.NumeroPessoas,
Preço = p.Preço,
Observaçoes = p.Observaçoes
}).ToList();
return Json(events, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(ex.Message);
}
}
[HttpPost]
public JsonResult SaveEvent(Reserva e)
{
var status = false;
using (HotelEntities dc = new HotelEntities())
{
if (e.ID_Reserva > 0)
{
//Update the event
var v = dc.Reserva.Where(a => a.ID_Reserva == e.ID_Reserva).FirstOrDefault();
if (v != null)
{
v.ID_Cliente = e.ID_Cliente;
v.DataEntrada = e.DataEntrada;
v.DataSaida = e.DataSaida;
v.ID_Quarto = e.ID_Quarto;
v.NumeroPessoas = e.NumeroPessoas;
v.NumeroNoites = e.NumeroNoites;
v.Preço = e.Preço;
v.Observaçoes = e.Observaçoes;
}
}
else
{
dc.Reserva.Add(e);
}
dc.SaveChanges();
status = true;
}
return new JsonResult { Data = new { status = status } };
}
[HttpPost]
public JsonResult DeleteEvent(int eventID)
{
var status = false;
using (HotelEntities dc = new HotelEntities())
{
var v = dc.Reserva.Where(a => a.ID_Reserva == eventID).FirstOrDefault();
if (v != null)
{
dc.Reserva.Remove(v);
dc.SaveChanges();
status = true;
}
}
return new JsonResult { Data = new { status = status } };
}
}
}
Model
public partial class Reserva
{
public int ID_Reserva { get; set; }
public int ID_Cliente { get; set; }
public int ID_Quarto { get; set; }
public System.DateTime DataEntrada { get; set; }
public Nullable<System.DateTime> DataSaida { get; set; }
public int NumeroPessoas { get; set; }
public Nullable<int> NumeroNoites { get; set; }
public Nullable<decimal> Preço { get; set; }
public string Observaçoes { get; set; }
public virtual Cliente Cliente { get; set; }
public virtual Quarto Quarto { get; set; }
}
Your event objects do not conform to the specification laid out at https://fullcalendar.io/docs/event-object .
Here is the problem:
$.each(data, function (i, v) {
events.push({
eventID: v.ID_Reserva,
clienteID: v.ID_Cliente,
quartoID: v.ID_Quarto,
inicio: moment(v.DataEntrada),
fim: v.DataSaida != null ? moment(v.DataSaida) : null,
noites: v.NumeroNoites,
pessoas: v.NumeroPessoas,
preço: v.Preço,
obs: v.Observaçoes
});
});
FullCalendar doesn't speak Portuguese. The event property names have to match the ones in the documentation otherwise it will ignore them. It doesn't magically know that inicio means start, for example. This means it cannot read any start time from your event, and therefore it doesn't know how to display it on the calendar.
Again as per the documentation, your events are also required to have a title, which you didn't appear to include at all.
Try this instead:
$.each(data, function (i, v) {
events.push({
id: v.ID_Reserva,
clienteID: v.ID_Cliente,
quartoID: v.ID_Quarto,
title: '[You need to choose something to put here]',
start: moment(v.DataEntrada),
end: v.DataSaida != null ? moment(v.DataSaida) : null,
noites: v.NumeroNoites,
pessoas: v.NumeroPessoas,
preço: v.Preço,
obs: v.Observaçoes
});
});
I have just changed the properties which matter for displaying the event. For other custom properties, you can call them anything you like, but the ones which have a defined purpose in fullCalendar must be named correctly.
P.S. You may need to change the code in your eventDrop function in a similar way.

knockout binding mvc not working

I experimenting something with mvc and knockout.js but maybe a have binding problem.
My viewmodel is:
var urlPath = window.location.pathname;
var currencyVm = function () {
var self = this;
var validationOptions = { insertMessages: true, decorateElement: true, errorElementClass: 'errorFill' };
ko.validation.init(validationOptions);
//ViewModel
self.ID = ko.observable(0);
self.Id_Region = ko.observable("");
self.Description = ko.observable("");
self.Symbol = ko.observable("");
self.PayPalCode = ko.observable("");
self.IFSCode = ko.observable("");
self.isGridVisible = ko.observable(true);
self.isEditVisible = ko.observable(false);
self.isAddVisible = ko.observable(false);
//Objects ---------------------------------------------
self.Currency = ko.observable();
self.Currencys = ko.observableArray([]);
//Methods ---------------------------------------------
//Edit
self.editCurrency = function (dataItem) {
self.isGridVisible(false);
self.isEditVisible(true);
self.ID = ko.observable(dataItem.ID);
self.Id_Region = ko.observable(dataItem.Id_Region);
self.Description = ko.observable(dataItem.Description);
self.Symbol = ko.observable(dataItem.Symbol);
self.PayPalCode = ko.observable(dataItem.PayPalCode);
self.IFSCode = ko.observable(dataItem.IFSCode);
//var vm = ko.mapping.fromJS(dataItem);
//self.Currency(vm);
};
//Add
self.addCurrency = function () {
self.isGridVisible(false);
self.isAddVisible(true);
self.isEditVisible(false);
self.reset();
}
// Cancel Edit
self.cancelEdit = function () {
self.isEditVisible(false);
self.isGridVisible(true);
}
// Cancel Add
self.cancelAdd = function () {
self.isAddVisible(false);
self.isGridVisible(true);
}
//Reset
self.reset = function () {
self.ID(0);
self.Id_Region("");
self.Description("");
self.Symbol("");
self.PayPalCode("");
self.IFSCode("");
}
//Actions --------------------------------------------------
var Currency = {
ID: self.ID,
Id_Region: self.Id_Region,
Description: self.Description,
Symbol: self.Symbol,
PayPalCode: self.PayPalCode,
IFSCode: self.IFSCode
};
//Create
self.createCurrency = function () {
$.ajax({
url: "/Currency/CreateCurrency",
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(Currency),
success: function (data) {
self.isEditVisible(false);
self.isAddVisible(false);
self.isGridVisible(true);
$("#gridCurrencies").data("kendoGrid").dataSource.read();
}
}).fail(
function (xhr, textStatus, err) {
alert(err);
});
}
// Update
self.updateCurrency = function () {
$.ajax({
url: "/Currency/UpdateCurrency",
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(Currency),
success: function (data) {
self.isEditVisible(false);
self.isEditVisible(false);
self.isGridVisible(true);
$("#gridCurrencies").data("kendoGrid").dataSource.read();
}
})
}
//Delete
self.deleteCurrency = function (currency) {
$.confirm({
title: "Delete",
content: "Sure to delete ?",
confirm: function () {
$.ajax({
url: "/Currency/DeleteCurrency",
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(currency),
success: function (data) {
$("#gridCurrencies").data("kendoGrid").dataSource.read();
}
}).fail(
function (xhr, textStatus, err) {
alert(err);
});
},
cancel: function () {
}
});
}
};
in the view I call applybinding and then based on selected row of the Telerik grid I call editCurrency or deleteCurrency.
<script>
var viewModel = null;
$(function () {
viewModel = new currencyVm();
ko.applyBindings(viewModel);
});
function deleteCurrency(e) {
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
viewModel.deleteCurrency(dataItem);
}
function editCurrency(e) {
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
viewModel.editCurrency(dataItem);
}
</script>
In the markup I have the html elements with the bindings:
Thi is the div for add:
<div class="panel panel-default" data-bind="visible: isAddVisible" style="display:none">
<div class="panel-heading">Add New Currency</div>
<div class="panel-body">
<div class="row">
<div class="col-md-3">
#Html.LabelFor(model => model.IFSCode)
<input type="text" data-bind="value: $root.IFSCode, valueUpdate: 'keypress'" class="form-control " />
</div>
<div class="col-md-3">
#Html.LabelFor(model => model.PayPalCode)
<input type="text" data-bind="value: $root.PayPalCode, valueUpdate: 'keypress'" class="form-control " />
</div>
<div class="col-md-3">
#Html.LabelFor(model => model.Symbol)
<input type="text" data-bind="value: $root.Symbol, valueUpdate: 'keypress'" class="form-control " />
</div>
</div>
<div class="row">
<div class="col-md-9">
#Html.LabelFor(model => model.Description)
<input type="text" data-bind="value: $root.Description" class="form-control" />
</div>
</div>
<br />
<div class="row">
<div class="col-md-3">
<input data-bind="click: $root.createCurrency" type="button" class="btn btn-success btn-sm" value="#DbRes.T("Save", "Common")" />
<input data-bind="click: cancelAdd" type="button" class="btn btn-warning btn-sm" value="#DbRes.T("Cancel", "Common")" />
</div>
</div>
</div>
the edit div is like the add div but use different binding like data-bind="value: IFSCode"
The problem is that in add mode it work but when I edit I dont see nothing
in the textbox elements.
Also I use the to debug,
in add mode I can see the observables updating while I type something in textbox,
in edit mode the observables are emtpy and remain while typeing something.
May some body help please to understand what appen to this code
Your help is very appreciated.

How to pass selected files in Kendo Upload as parameter in ajax request

After much of struggle im posing this question. Im using a Kendo Upload on a page. Am able to post the selected files on the asyn mode with whe the page has Html.BeginForm. But I'm not able to send file details as HttpPostedFileBase when I use ajax request to send data to the controller.
Following is my html
<form class="form-horizontal" role="form">
<div class="form-group">
#Html.Label("Complaint Name", new { #class = "col-sm-3 control-label" })
<div class="col-sm-4">
#Html.TextBoxFor(
m => m.ComplaintName,
new
{
#TabIndex = "1",
#class = "form-control input-sm",
disabled = true
})
</div>
</div>
<div class="form-group">
#Html.Label("Complaint Details", new { #class = "col-sm-3 control-label" })
<div class="col-sm-4">
#Html.TextBoxFor(
m => m.ComplaintDetails,
new
{
#TabIndex = "2",
#class = "form-control input-sm",
disabled = true
})
</div>
</div>
<div class="form-group">
#Html.Label("Choose files to upload", new { #class = "col-sm-3 control-label" })
<div class="col-sm-9 nopaddingforTextArea">
<input name="files" id="files" type="file" />
</div>
</div>
<div class="form-group">
<div>
<input id="btnSubmit" class="btn btn-primary pull-right" type="button" />
</div>
</div>
</form>
Following is my action
public ActionResult SaveComplaintDetails(string complaintName, string complaintDetails, IEnumerable<HttpPostedFileBase> files)
{
}
Following is my js
$("#files").kendoUpload({
async: {
saveUrl: '#Url.Action("EsuperfundCommentsBind", ClientInboxConstants.NewQuery)',
autoUpload: false
},
multiple: true
});
$("#btnSubmit").click(function () {
//Ajax call from the server side
$.ajax({
//The Url action is for the Method FilterTable and the Controller PensionApplicationList
url: '#Url.Action("SaveComplaintDetails", "Complaints")',
//The text from the drop down and the corresponding flag are passed.
//Flag represents the Index of the value in the dropdown
data: {
complaintName: document.getElementById("ComplaintName").value,
complaintDetails: document.getElementById("ComplaintDetails").value,
files: //What to pass here??
},
contentType: "application/json; charset=utf-8",
//Json data
datatype: 'json',
//Specify if the method is GET or POST
type: 'GET',
//Error function gets called if there is an error in the ajax request
error: function () {
},
//Gets called on success of the Ajax Call
success: function (data) {
}
});
});
My question is how to pass the selected files in Kendo Upload in ajax as a parameter?
Any help in this aspect would be really appreciated.
If your view is based on a model and you have generated the controls inside <form> tags, then you can serialize the model to FormData using:
<script>
var formdata = new FormData($('form').get(0));
</script>
This will also include any files generated with: <input type="file" name="myImage" .../> and post it back using:
<script>
$.ajax({
url: '#Url.Action("YourActionName", "YourControllerName")',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
});
</script>
and in your controller:
[HttpPost]
public ActionResult YourActionName(YourModelType model)
{
}
or (if your model does not include a property for HttpPostedFileBase)
[HttpPost]
public ActionResult YourActionName(YourModelType model,
HttpPostedFileBase myImage)
{
}
If you want to add additional information that is not in the form, then you can append it using
<script>
formdata.append('someProperty', 'SomeValue');
</script>
**Example Usage :**
View :
#using (Html.BeginForm("Create", "Issue", FormMethod.Post,
new { id = "frmCreate", enctype = "multipart/form-data" }))
{
#Html.LabelFor(m => m.FileAttachments, new { #class = "editor-label" })
#(Html.Kendo().Upload()
.HtmlAttributes(new { #class = "editor-field" })
.Name("files")
)
}
<script>
$(function () {
$('form').submit(function (event) {
event.preventDefault();
var formdata = new FormData($('#frmCreate').get(0));
$.ajax({
type: "POST",
url: '#Url.Action("Create", "Issue")',
data: formdata,
dataType: "json",
processData: false,
contentType: false,
success: function (response) {
//code omitted for brevity
}
});
});
});
</script>
*Controller :*
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = null)] Model viewModel, IEnumerable<HttpPostedFileBase> files)
{
//code omitted for brevity
return Json(new { success = false, message = "Max. file size 10MB" }, JsonRequestBehavior.AllowGet);
}
<script>
$(function () {
$('form').submit(function (event) {
event.preventDefault();
var formdata = new FormData($('#createDetail').get(0));
$.ajax(
{
type: 'POST',
url: '#Url.Action("Detail_Create", "Product")',
data: formdata,
processData: false,
success: function (result) {
if (result.success == false) {
$("#divErr").html(result.responseText);
} else {
parent.$('#CreateWindowDetail').data('kendoWindow').close();
}
},
error: function (xhr, ajaxOptions, thrownError) {
$("#divErr").html(xhr.responseText);
}
});
});
});
#using (Html.BeginForm("Detail_Create", "Product", FormMethod.Post, new { id = "createDetail", enctype="multipart/form-data"}))
{
<div id="divErr" class="validation-summary-errors"></div>
<fieldset>
<ol>
<li>
#Html.LabelFor(m => m.Price)
#(Html.Kendo().NumericTextBoxFor(m => m.Price).Name("Price").Format("{0:0}")
.HtmlAttributes(new { style = "width:100%" })
)
</li>
<li>
#Html.LabelFor(m => m.Description)
#Html.TextBoxFor(model => model.Description, new { #class = "k-textbox", id = "Description", style = "width:100%;" })
</li>
<li>
#Html.LabelFor(m => m.Group)
#(Html.Kendo().ComboBox()
.Name("Group")
.Placeholder("Введите группу детали")
.DataTextField("Name")
.DataValueField("Id")
.HtmlAttributes(new { style = "width:100%;" })
.Filter("contains")
.MinLength(1)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Group_Read_ComboBox", "Product");
})
.ServerFiltering(true);
})
)
</li>
<li>
#Html.LabelFor(m => m.Image)
#(Html.Kendo().Upload()
.Name("files")
)
</li>
</ol>
</fieldset>
<button type="submit" id="get" class="k-button">Добавить</button>
}
[HttpPost]
public ActionResult Detail_Create(DetailModel model, IEnumerable<HttpPostedFileBase> files)
{
string error = string.Empty;
if (ModelState.IsValid)
{
.....
}
IEnumerable<System.Web.Mvc.ModelError> modelerrors = ModelState.SelectMany(r => r.Value.Errors);
foreach (var modelerror in modelerrors)
{
error += "• " + modelerror.ErrorMessage + "<br>";
}
return Json(new { success = false, responseText = error }, JsonRequestBehavior.AllowGet);
}
after pressing the button, the controller null comes to how to fix. 2 days already sitting, and the time comes to an end

Resources