Good Evening,
I'm trying to upload a file and when the form submits I just want to reload the partial view in the modal div, not the entire page. I looked at a number of other posts and they suggested to use AJAX but even when I used AJAX, instead of just reloading the partial view popup, It takes me to a full page view of the Partial View. I want to just reload the content inside of the modal div.
Here is my code:
Controller
public PartialViewResult FileUpload(int jobID)
{
ViewBag.jobID = jobID;
return PartialView(GetFiles(jobID));
}
[HttpPost]
public ActionResult FileUpload(int jobID, HttpPostedFileBase files)
{
int id = Convert.ToInt32(Session["id"]);
String FileExt = Path.GetExtension(files.FileName).ToUpper();
if(FileExt == ".PDF")
{
Stream str = files.InputStream;
BinaryReader Br = new BinaryReader(str);
Byte[] FileDet = Br.ReadBytes((Int32)str.Length);
UploadFileModel Fd = new UploadFileModel();
Fd.FileName = files.FileName;
Fd.FileContent = FileDet;
Fd.personID = id;
Fd.jobID = jobID;
file fileDB = new file();
fileDB.FileContent = Fd.FileContent;
fileDB.FileName = Fd.FileName;
fileDB.personID = id;
fileDB.jobID = Fd.jobID;
db.files.Add(fileDB);
db.SaveChanges();
return PartialView("FileUpload", GetFiles(jobID));
}
else
{
ViewBag.FileStatus = "Invalid file format.";
return PartialView();
}
}
[HttpPost]
public FileResult DownloadFile(int? fileId)
{
byte[] bytes;
string fileName, contentType;
var file = db.files.Find(fileId);
bytes = (byte[])file.FileContent;
fileName = file.FileName;
return File(bytes, fileName);
}
public List<UploadFileModel> GetFiles(int jobID)
{
List<UploadFileModel> files = new List<UploadFileModel>();
var filesDB = db.files.Where(x => x.jobID == jobID);
foreach (var fileDB in filesDB)
{
files.Add(new UploadFileModel
{
id = fileDB.id,
FileName = fileDB.FileName,
personID = fileDB.personID,
jobID = fileDB.jobID
});
}
return files;
}
Partial View:
#model IEnumerable<Church_Musician_Administration_App__Updated_.Models.UploadFileModel>
<style>
.table-striped tbody tr:nth-of-type(odd) {
background-color: rgb(222, 178, 241);
}
.table-striped tbody tr:nth-of-type(even) {
background-color: rgb(233, 204, 246);
}
#fileTable {
font-family: "Arial";
}
#fileTable tr {
cursor: default;
}
a:link {
color: darkviolet;
background-color: transparent;
text-decoration: none;
}
a:visited {
color: gray;
background-color: transparent;
text-decoration: none;
}
a:hover {
color: white;
background-color: transparent;
text-decoration: none;
}
a:active {
color: rebeccapurple;
background-color: transparent;
text-decoration: none;
}
</style>
#using (Html.BeginForm("FileUpload", "App", FormMethod.Post, new { enctype = "multipart/form-data", id="fileUploadForm"}))
{
<input type="hidden" name="jobID" value="#ViewBag.jobID" />
<label class="btn btn-primary" for="my-file-selector">
<input id="my-file-selector" name="files" type="file" style="display:none"
onchange="$('#upload-file-info').text(this.files[0].name)">
Choose File
</label>
<span class='label label-info' id="upload-file-info">No File Uploaded</span>
<input class="btn btn-primary" type="submit" id="btnUpload" value="Upload" style="margin-bottom:5px" />
}
#using (Html.BeginForm("DownloadFile", "App", FormMethod.Post))
{
<input type="hidden" id="hfFileId" name="FileId" />
<input type="submit" id="btnDownload" value="Download" style="display:none" />
}
<hr />
<table id="fileTable" class="table table-striped" style="width:100%; border: 1px solid rgba(0,0,0,.125); border-left:none; border-right:none; text-align: center; display:inline-table;">
<tbody>
<tr style="background-color:darkviolet; height:40px; width:100%">
<th style="display:none;">JobID</th>
<th style="display:none">File ID</th>
<th style="color:white; border: 1px solid rgba(0,0,0,.125);">File Name</th>
<th style="color:white; border: 1px solid rgba(0,0,0,.125);">Download</th>
</tr>
#if (Model.Count() > 0)
{
foreach (var file in Model)
{
<tr>
<td style="display:none;">#file.id</td>
<td style="border: 1px solid rgba(0,0,0,.125);">#file.FileName</td>
<td style="border: 1px solid rgba(0,0,0,.125);">Download</td>
</tr>
}
}
else
{
<tr>
<td colspan="3"> </td>
</tr>
}
</tbody>
</table>
<script type="text/javascript">
function DownloadFile(fileId) {
$("#hfFileId").val(fileId);
$("#btnDownload")[0].click();
};
</script>
<script>
$('#btnUpload').click(function (event) {
event.preventDefault();
event.stopImmediatePropagation();
$('#fileUploadForm').submit();
$.ajax({
url: '/App/FileUpload',
type: 'POST',
success: function (data) {
$("#addMusicModalBodyDiv").html(data);
$("#addMusicModal").modal("show");
}
});
});
</script>
EDIT: Here is the code for where the addMusicModal is defined. It's located in a view called ViewSubstituteJobs
<button type="button" class="btn btn-primary" id="addMusic" onclick="addMusic()">Add Music</button>
<div class="modal" tabindex="-1" id="addMusicModal">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add Music</h5>
<button type="button" class="close" aria-label="Close" id="closeAddMusicModal" onclick="closeDialog()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="addMusicModalBodyDiv">
</div>
</div>
</div>
</div>
var addMusic = function () {
var idFromTable = $("#subJobs tr").closest('tr.highlight').find('td:eq(0)').text();
if (idFromTable == 0) {
return false;
}
$.ajax({
type: "GET",
url: "/App/FileUpload",
data: {
jobID: idFromTable,
},
success: function (response) {
$(".modal").modal("hide");
$("#addMusicModalBodyDiv").html(response);
$("#addMusicModal").modal("show");
}
})
}
</script>
Related
I want to save my coordinates from the frontend to the backend and I don't know how to send them.
the coordinates are saved in a JS array and I don't know how to transfer them to C#.
HTML, CSS & JS for the map
<link rel="stylesheet" href="~/css/ol.css">
<link rel="stylesheet" href="~/css/ol-ext.css">
<script src="~/js/ol.js"></script>
<script src="~/js/ol-ext.js"></script>
#*<script src="~/js/elm-pep"></script>*#
#*<script src="~/js/JavaScript.js"></script>*#
<div id="map" style="width:600px; height:400px;">
<div class="photon ol-search ol-unselectable ol-control ol-collapsed">
<input asp-for="coordinates" type="search" class="search" autocomplete="off" placeholder="Search...">
<input asp-for="coordinates" type="button" class="ol-revers" title="click on the map">
<ul class="autocomplete history">
<li data-search="0"> 398<i> 9350004 Jérusalem (Israël)</i></li>
<li class="copy">© OpenStreetMap contributors</li>
</ul>
</div>
</div>
<div class="button-70" style="z-index:1;" id="location-button">
#*<button id="location-button" title="Get your location"></button>*#
#*<button asp-for="coordinates" class="button-70" id="location-button" role="button" title="Get your current location">📍 Get cuttent location</button>*#
<input asp-for="coordinates" type="button" value="📍 Get cuttent location" id="location-button" />
</div>
<style>
.button-70 #location-button {
background: none;
border: none;
transform: scale(2)
}
.button-70 {
transform: scale(0.7);
background-image: linear-gradient(#0dccea, #0d70ea);
border: 0;
border-radius: 4px;
box-shadow: rgba(0, 0, 0, .3) 0 5px 15px;
box-sizing: border-box;
color: #fff;
cursor: pointer;
font-family: Montserrat,sans-serif;
font-size: .9em;
margin: 5px;
padding: 10px 15px;
text-align: center;
user-select: none;
-webkit-user-select: none;
touch-action: manipulation;
}
</style>
<script type="text/javascript">
var layers = [new ol.layer.Tile({ source: new ol.source.OSM() })];
var map = new ol.Map({
target: 'map',
view: new ol.View({
zoom: 5,
center: [166326, 5992663]
}),
interactions: ol.interaction.defaults({ altShiftDragRotate: false, pinchRotate: false }),
layers: layers
});
var search = new ol.control.SearchPhoton({
lang: "fr",
reverse: true,
position: true
});
map.addControl(search);
var markers;
search.on('select', function (e) {
map.getView().animate({
center: e.coordinate,
zoom: Math.max(map.getView().getZoom(), 16)
});
loc(e.coordinate);
});
function loc(e) {
console.log(e);
if (markers) {
map.removeLayer(markers)
}
markers = new ol.layer.Vector({
source: new ol.source.Vector(),
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 1],
src: 'https://ucarecdn.com/4b516de9-d43d-4b75-9f0f-ab0916bd85eb/marker.png' // => https://app.uploadcare.com/projects/c05bbeb5e1a61e862903/files/7110cd57-b0ee-4833-bcd1-ff0343dd01cc/?limit=100&ordering=-datetime_uploaded
})
})
});
map.addLayer(markers);
var marker = new ol.Feature(new ol.geom.Point(e));
markers.getSource().addFeature(marker);
}
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
document.querySelector("#location-button").addEventListener("click", function (e) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
console.log(e);
if (markers) {
map.removeLayer(markers)
}
markers = new ol.layer.Vector({
source: new ol.source.Vector(),
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 1],
src: 'https://ucarecdn.com/4b516de9-d43d-4b75-9f0f-ab0916bd85eb/marker.png' // => https://app.uploadcare.com/projects/c05bbeb5e1a61e862903/files/7110cd57-b0ee-4833-bcd1-ff0343dd01cc/?limit=100&ordering=-datetime_uploaded
})
})
});
map.addLayer(markers);
function success(pos) {
const crd = pos.coords;
console.log('Your current position is:');
console.log(`Latitude : ${crd.latitude}`);
console.log(`Longitude: ${crd.longitude}`);
console.log(`More or less ${crd.accuracy} meters.`);
return new Array(crd.latitude, crd.longitude);
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
navigator.geolocation.getCurrentPosition(success, error, options);
var marker = new ol.Feature(new ol.geom.Point(ol.proj.fromLonLat([position.coords.latitude, position.coords.longitude])));
markers.getSource().addFeature(marker);
});
}
else {
alert("Your browser does not support geolocation");
}
});
</script>
I tried to save the coordinates in A list and in a string, but none worked.
here is the Model code:
public class ReportModel
{
//...stuff...
public string coordinates { get; set; }
//...more stuff...
}
ReportDAO.cs - Saves the given data form the user
using Microsoft.Data.SqlClient;
using SvivaTeamVersion3.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SvivaTeamVersion3.Services
{
public class ReportDAO
{
static readonly string connectionString = #"KEY";
public static bool addReport(ReportModel report)
{
bool success = false;
string sqlStatement = "INSERT INTO dbo.Reports (category,title,description,statUrgence,cordsLat,cordsLong) VALUES (#category,#title,#description,#statUrgence,#cordsLat,#cordsLong)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(sqlStatement, connection);
command.Parameters.Add("#category", System.Data.SqlDbType.NChar, 32).Value = report.category;
command.Parameters.Add("#title", System.Data.SqlDbType.NChar, 32).Value = report.title;
command.Parameters.Add("#description", System.Data.SqlDbType.NVarChar, -1).Value = report.remarks;
command.Parameters.Add("#statUrgence", System.Data.SqlDbType.NVarChar, -1).Value = report.statUrgence;
command.Parameters.Add("#cordsLat", System.Data.SqlDbType.Float).Value = report.coordinates;
command.Parameters.Add("#cordsLong", System.Data.SqlDbType.Float).Value = 0;
//I've tried to merge the lat and long to a single string, didn't work.
try
{
connection.Open();
command.ExecuteNonQuery();
success = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return success;
}
}
}
}
I'm creating a web site, where I have a list of classes, and I want that each class will have it`s own calendar. What I mean is, when I click button 1, I will go to a separate calendar then button 2 and so on.
I already have a working calendar, I just don't understand how assign to each button a calendar.
So I have a working calendar with options of add/delete/update events, but I don't understand how to connect them.
I'm on this problem over a week now, and I couldn't find any solution. help please.
This is the index.cshtml where the classes are created: (classes view)
#model IEnumerable<ClasSaver.Models.ClassesModel>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<style>
.button {
background-color: deepskyblue; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
</style>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Building)
</th>
<th>
#Html.DisplayNameFor(model => model.How_Many_In_Class)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Building)
</td>
<td>
#Html.DisplayFor(modelItem => item.How_Many_In_Class)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
#Html.ActionLink("Details", "Details", new { id = item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
<input id="#item.Id" type="button" onclick="parent.open('https://www.google.com/')" value="Open in new window" class="button">
</td>
</tr>
}
</table>
<script>
</script>
and the controller
using ClasSaver.Data;
using ClasSaver.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ClasSaver.Controllers
{
public class ClassesController : Controller
{
// GET: Classes
public ActionResult Index()
{
List<ClassesModel> classes = new List<ClassesModel>();
ClassDAO classDao = new ClassDAO();
classes = classDao.FetchAll();
return View("Index",classes);
}
public ActionResult Details(int id)
{
ClassDAO classesDAO = new ClassDAO();
ClassesModel classes = classesDAO.FetchOne(id);
return View("Details", classes);
}
public ActionResult Create(ClassesModel classesModel)
{
return View("ClassesForm", classesModel);
}
[HttpPost]
public ActionResult ProcessCreate(ClassesModel classesModel)
{
//save to DB
ClassDAO classesDAO = new ClassDAO();
classesDAO.CreateOrUpdate(classesModel);
return View("Details", classesModel);
}
public ActionResult Edit(int id)
{
ClassDAO classesDAO = new ClassDAO();
ClassesModel classes = classesDAO.FetchOne(id);
return View("ClassesForm", classes);
}
public ActionResult Delete(int id)
{
ClassDAO classesDAO = new ClassDAO();
classesDAO.Delete(id);
List<ClassesModel> classes = classesDAO.FetchAll();
return View("Index", classes);
}
public ActionResult SearchForm()
{
return View("SearchForm");
}
[HttpPost]
public ActionResult searchForName(string searchPhrase)
{
ClassDAO classesDAO = new ClassDAO();
List<ClassesModel> searchResults = classesDAO.SearchForName(searchPhrase);
return View("Index", searchResults);
}
}
}
and this is where the calendar is created index.cshtml: (home view)
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<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> Remove
</button>
<button id="btnEdit" class="btn btn-default btn-sm pull-right" style="margin-right:5px;">
<span class="glyphicon glyphicon-pencil"></span> Edit
</button>
<p id="pDetails"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</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">Save Event</h4>
</div>
<div class="modal-body">
<form class="form-horizontal">
<input type="hidden" id="hdEventID" value="0" />
<div class="form-group">
<label>Subject</label>
<input type="text" id="txtSubject" class="form-control" />
</div>
<div class="form-group">
<label>Start</label>
<div class="input-group date" id="dtp1">
<input type="text" id="txtStart" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label><input type="checkbox" id="chkIsFullDay" checked="checked" /> Is Full Day event</label>
</div>
</div>
<div class="form-group" id="divEndDate" style="display:none">
<label>End</label>
<div class="input-group date" id="dtp2">
<input type="text" id="txtEnd" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<label>Description</label>
<textarea id="txtDescription" rows="3" class="form-control"></textarea>
</div>
<div class="form-group">
<label>Theme Color</label>
<select id="ddThemeColor" class="form-control">
<option value="">Default</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="black">Black</option>
<option value="green">Green</option>
</select>
</div>
<button type="button" id="btnSave" class="btn btn-success">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</form>
</div>
</div>
</div>
</div>
<link href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.css" rel="stylesheet" />
<link href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.print.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://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.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: "/home/GetEvents",
success: function (data) {
$.each(data, function (i, v) {
events.push({
eventID: v.EventID,
title: v.Subject,
description: v.Description,
start: moment(v.Start),
end: v.End != null ? moment(v.End) : null,
color: v.ThemeColor,
allDay: v.IsFullDay
});
})
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.title);
var $description = $('<div/>');
$description.append($('<p/>').html('<b>Start:</b>' + calEvent.start.format("DD-MMM-YYYY HH:mm a")));
if (calEvent.end != null) {
$description.append($('<p/>').html('<b>End:</b>' + calEvent.end.format("DD-MMM-YYYY HH:mm a")));
}
$description.append($('<p/>').html('<b>Description:</b>' + calEvent.description));
$('#myModal #pDetails').empty().html($description);
$('#myModal').modal();
},
selectable: true,
select: function (start, end) {
selectedEvent = {
eventID: 0,
title: '',
description: '',
start: start,
end: end,
allDay: false,
color: ''
};
openAddEditForm();
$('#calendar').fullCalendar('unselect');
},
editable: true,
eventDrop: function (event) {
var data = {
EventID: event.eventID,
Subject: event.title,
Start: event.start.format('DD/MM/YYYY HH:mm A'),
End: event.end != null ? event.end.format('DD/MM/YYYY HH:mm A') : null,
Description: event.description,
ThemeColor: event.color,
IsFullDay: event.allDay
};
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: '/home/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'
});
$('#chkIsFullDay').change(function () {
if ($(this).is(':checked')) {
$('#divEndDate').hide();
}
else {
$('#divEndDate').show();
}
});
function openAddEditForm() {
if (selectedEvent != null) {
$('#hdEventID').val(selectedEvent.eventID);
$('#txtSubject').val(selectedEvent.title);
$('#txtStart').val(selectedEvent.start.format('DD/MM/YYYY HH:mm A'));
$('#chkIsFullDay').prop("checked", selectedEvent.allDay || false);
$('#chkIsFullDay').change();
$('#txtEnd').val(selectedEvent.end != null ? selectedEvent.end.format('DD/MM/YYYY HH:mm A') : '');
$('#txtDescription').val(selectedEvent.description);
$('#ddThemeColor').val(selectedEvent.color);
}
$('#myModal').modal('hide');
$('#myModalSave').modal();
}
$('#btnSave').click(function () {
//Validation/
if ($('#txtSubject').val().trim() == "") {
alert('Subject required');
return;
}
if ($('#txtStart').val().trim() == "") {
alert('Start date required');
return;
}
if ($('#chkIsFullDay').is(':checked') == false && $('#txtEnd').val().trim() == "") {
alert('End date required');
return;
}
else {
var startDate = moment($('#txtStart').val(), "DD/MM/YYYY HH:mm A").toDate();
var endDate = moment($('#txtEnd').val(), "DD/MM/YYYY HH:mm A").toDate();
if (startDate > endDate) {
alert('Invalid end date');
return;
}
}
var data = {
Id: $('#hdEventID').val(),
Subject: $('#txtSubject').val().trim(),
Start: $('#txtStart').val().trim(),
End: $('#chkIsFullDay').is(':checked') ? null : $('#txtEnd').val().trim(),
Description: $('#txtDescription').val(),
ThemeColor: $('#ddThemeColor').val(),
IsFullDay: $('#chkIsFullDay').is(':checked')
}
SaveEvent(data);
// call function for submit data to the server
})
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '/home/SaveEvent',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function () {
alert('Failed');
}
})
}
})
</script>
}
and the controller
using ClasSaver.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ClasSaver.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public JsonResult GetEvents()
{
using (ClassaverDBEntities2 dc = new ClassaverDBEntities2())
{
var events = dc.Events.ToList();
return new JsonResult { Data = events, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
[HttpPost]
public JsonResult SaveEvent(Event e)
{
var status = false;
using (ClassaverDBEntities2 dc = new ClassaverDBEntities2())
{
if (e.EventID > 0)
{
//Update the event
var v = dc.Events.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
v.Subject = e.Subject;
v.Start = e.Start;
v.End = e.End;
v.Description = e.Description;
v.IsFullDay = e.IsFullDay;
v.ThemeColor = e.ThemeColor;
}
}
else
{
dc.Events.Add(e);
}
dc.SaveChanges();
status = true;
}
return new JsonResult { Data = new { status = status } };
}
[HttpPost]
public JsonResult DeleteEvent(int eventID)
{
var status = false;
using (ClassaverDBEntities2 dc = new ClassaverDBEntities2())
{
var v = dc.Events.Where(a => a.EventID == eventID).FirstOrDefault();
if (v != null)
{
dc.Events.Remove(v);
dc.SaveChanges();
status = true;
}
}
return new JsonResult { Data = new { status = status } };
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
I am dynamically adding columns to a Web-grid using MVC-5 and C# and when the grid renders everything looks fine but the column headers won't function as an action Links. There are two versions of the code and both render but don't function as Action Links.
Thank you for your help.
cols.Add(grid.Column(Model.DictionaryList[i].Keys.ElementAt(i).ToString(), Model.DictionaryList[i].Keys.ElementAt(i).ToString(),
format: #<Text>#Html.ActionLink((string)Model.DictionaryList[i].Values.ElementAt(i).ToString(), "Select_MSPart_Search",
"MaterialSupply", new
{
id = ViewData["id"],
type = 1,
SearchFilter = Model.DictionaryList[i].Keys.ElementAt(i).ToString(),
SearchValue = "",
rowsPerPage = 7
})</Text>, style: "column-action"));
cols.Add(grid.Column(header: Model.DictionaryList[i].Keys.ElementAt(i).ToString(),columnName: Model.DictionaryList[i].Keys.ElementAt(i).ToString(),
format: (item) => new HtmlString(Html.ActionLink((string)Model.DictionaryList[i].Values.ElementAt(i).ToString(), "Select_MSPart_Search",
"MaterialSupply", new
{
id = ViewData["id"],
type = 1,
SearchFilter = Model.DictionaryList[i].Keys.ElementAt(i).ToString(),
SearchValue = "",
rowsPerPage = 7
},null).ToHtmlString()), style: "column-action"));
Everything seems to render correctly except the column headers are not Action Links as I had hoped for. I also tried the second piece of code with the same results.
Thank you for your help.
I realized that seeing the entire view would be critical because I am building the grid dynamically.
#using System.Dynamic
#using System.Linq
#using System.Data.Common
#using CeleroPortal.Models.ConstraintsAnalysis
#using System.Collections.Generic
#using System.Web.Mvc.Html
#using System.Web.Mvc.Razor
#model mdlViews
#using PagedList.Mvc
#{
ViewBag.Title = "View Report records Page";
var result = new List<dynamic>();
int rowcnt = 0;
foreach (var recRow in Model.DlList)
{
var row = (IDictionary<string, object>)new ExpandoObject();
Dictionary<string, object> eachFieldRow = (Dictionary<string, object>)recRow; //for when list was string,object
foreach (KeyValuePair<string, object> keyValuePair in eachFieldRow)
{
row.Add(keyValuePair.Key, keyValuePair.Value);
}
result.Add(row);
rowcnt++;
}
//WebGrid grid = new WebGrid(source: result, rowsPerPage: Model.PageSize, canPage: true, canSort: true, sortFieldName: Model.Sort, sortDirectionFieldName: Model.SortDir);
WebGrid grid = new WebGrid(rowsPerPage: Model.PageSize, canPage: true, canSort: false, sortFieldName: Model.Sort, sortDirectionFieldName: Model.SortDir);
List<WebGridColumn> cols = new List<WebGridColumn>();
cols.Add(grid.Column("Order ID","Order ID"));
cols.Add(grid.Column("Part ID", "Part ID"));
cols.Add(grid.Column("Description", "Description"));
cols.Add(grid.Column("Customer ID", "Customer ID"));
cols.Add(grid.Column("Customer", "Customer"));
cols.Add(grid.Column("Qty Due", "Quantity Due"));
cols.Add(grid.Column("Target Date", "Target Date"));
cols.Add(grid.Column("Days", "Days"));
cols.Add(grid.Column("Final Date", "Final Date"));
for (int i = 9; i < Model.DictionaryList[0].Count(); i++)
{
if (Model.DictionaryList[0].Keys.ElementAt(i).StartsWith("#"))
{
cols.Add(grid.Column(Model.DictionaryList[0].Keys.ElementAt(i).ToString(), Model.DictionaryList[0].Keys.ElementAt(i).ToString()));
}
else
{
//cols.Add(grid.Column(Model.DictionaryList[i].Keys.ElementAt(i).ToString(),header: Model.DictionaryList[i].Keys.ElementAt(i).ToString(),
// format: (Model) => Html.ActionLink((string)Model.DictionaryList[i].Values.ElementAt(i).ToString(), "Select_MSPart_Search",
// "MasterSupply",new { id = ViewData["id"] , type = 1, SearchFilter = Model.DictionaryList[i].Keys.ElementAt(i).ToString() , SearchValue = "",
// rowsPerPage = 7}),style: "column-action"));
cols.Add(grid.Column(header:Model.DictionaryList[i].Keys.ElementAt(i).ToString(),columnName: Model.DictionaryList[i].Keys.ElementAt(i).ToString(),
format: #<Text>#Html.ActionLink((string)Model.DictionaryList[i].Values.ElementAt(i).ToString(), "Select_MSPart_Search",
"MaterialSupply", new
{
id = ViewData["id"],
type = 1,
SearchFilter = Model.DictionaryList[i].Keys.ElementAt(i).ToString(),
SearchValue = "",
rowsPerPage = 7
})</Text>, style: "column-action"));
//cols.Add(grid.Column(header: Model.DictionaryList[i].Keys.ElementAt(i).ToString(),columnName: Model.DictionaryList[i].Keys.ElementAt(i).ToString(),
// format: (item) => #Html.ActionLink((string)Model.DictionaryList[i].Values.ElementAt(i).ToString(), "Select_MSPart_Search",
// "MaterialSupply", new
// {
// id = ViewData["id"],
// type = 1,
// SearchFilter = Model.DictionaryList[i].Keys.ElementAt(i).ToString(),
// SearchValue = "",
// rowsPerPage = 7
// }, null)));
}
}
grid.Bind(result, rowCount: Model.TotalRecords, autoSortAndPage: true);
grid.Pager(WebGridPagerModes.All);
}
<style type="text/css">
.webgrid-table {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
font-size: 1.2em;
width: 100%;
display: table;
border-collapse: separate;
border: solid 1px #000066; /*#98BF21;*/
background-color: white;
}
.webgrid-table td, th {
border: 1px solid #000099; /*#98BF21;*/
padding: 3px 7px 2px;
}
.webgrid-header {
background-color: #b3d9ff; /*#A7C942;*/
color: #FFFFFF;
padding-bottom: 4px;
padding-top: 5px;
text-align: left;
}
.webgrid-footer {
}
.webgrid-row-style {
padding: 3px 7px 2px;
}
.webgrid-alternating-row {
background-color: #e6f2ff; /*#EAF2D3;*/
padding: 3px 7px 2px;
}
.webgrid-selected-row {
background-color: #ffff66; /*#EAF2D3;*/
padding: 3px 7px 2px;
}
</style>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<div class="jumbotron">
<h1><img src="~/Images/Celero.png" /></h1>
<p class="lead">Constraints Analysis Application Pushed Orders Grid</p>
<div>
#Html.ActionLink("Search for Part across reports", "Select_MSPart", "MaterialSupply", new { id = ViewData["Id"].ToString(), type = ViewData["type"]},null)
</div>
</div>
<div class="row">
#using (Html.BeginForm("Views", "ConstraintsAnalysis", new { id = ViewData["id"], type = ViewData["type"] }, FormMethod.Post))
{
<div class="row">
<div class="form-horizontal" style="float: left">
<div class="col-md-4">
#if (Model.RwsPrPge == Model.TotalRecords)
{
<select id="rwsPrPge" name="rwsPrPge">
<option value="5">50</option>
<option value="0">All</option>
</select>
}
else
{
<select id="rwsPrPge" name="rwsPrPge">
<option value="0">All</option>
<option value="5">50</option>
</select>
}
<input type="submit" value="Rows/Page" />
#Html.Hidden("id", (object)ViewData["Id"].ToString())
#Html.Hidden("type", (object)ViewData["type"].ToString())
</div>
<div class="col-lg-4">
#*#Html.DropDownListFor(Model => Model.SearchFilter, new SelectList(ViewBag.SelectFilter, "Value", "Text"),
"Select Part for Search", new { #class = "form-control", #placeholder = "Search Filter" })*#
#Html.DropDownList("m", new SelectList(ViewBag.SelectFilter, "Value", "Text"), "Select Part")
</div>
<div class="col-lg-4" float="right">
<button type="submit" class="btn btn-success" value="m">
<span class="glyphicon glyphicon-search"></span>
</button>
</div>
<br /><br />
<div class="col-md-4">
<select id="Export" name="Export">
<option value="00">No Export</option>
<option value="XX">Export to CSV</option>
#Html.EditorFor(model => model.DlList)
#Html.ValidationMessageFor(model => model.DlList)
</select>
</div>
<div class="col-md-4">
<button type="submit" class="btn btn-success" value="Export" href="/ConstraintsAnalysis/Views">
<span class="glyphicon glyphicon-export"></span>
</button>
</div>
</div>
</div>
if (Model != null)
{
<span>
<span class="vam" style="float: left">
#Html.ActionLink("Report Selection Menu", "Index", "ConstraintsAnalysis")
</span>
<span class="vam">
#grid.GetHtml(tableStyle: "table table-bordered table-hover",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
caption: "Celero Constraints Grid",
rowStyle: "webgrid-row-style");
</span>
</span>
}
}
</div>
I found the problem. I forgot the columns: cols on the #grid.GetHtml.
Thank you
I currently have table that displays a list of all of the issues. I added PagedList.MVC to the application as well as a jquery filterTable the issue is that when I click on a different page using the PagedListPager it loses all of the sort options at the top of the page. I believe I just need to add the parameters to the pagedlistpager but I am not sure how to get the value of the textbox. I was thinking about trying to use jquery and using the val() of the element but not sure if that is the best/easiest way to do this.
Here is my View:
#model PagedList.IPagedList<ApIssues.Models.AP_Tasks>
#using System.Data.SqlClient
#using PagedList.Mvc;
#{
ViewBag.Title = "Index";
}
<div class="search-sort-section">
<h2>Search and Sort</h2>
#using (Html.BeginForm("Index","ApIssues"))
{
<p>
#Html.Label("Company: ")
#Html.DropDownList("company", (SelectList)ViewBag.CompanyList, " ")
#Html.Label("Warehouse: ")
#Html.DropDownList("warehouse", (SelectList)ViewBag.WarehouseList, " ")
#Html.Label("Past Due Only: ")
#Html.DropDownList("pastDue", (SelectList)ViewBag.PastDueList, " ")
#Html.Label("Assigned To/By: ")
#Html.DropDownList("assignedToBy", (SelectList)ViewBag.UsersList, " ")
</p>
<p>
#Html.Label("Open / Completed: ")
#Html.DropDownList("openco", (SelectList)ViewBag.OpenCompList, " ")
#Html.Label("Sort By: ")
#Html.DropDownList("sortBy", (SelectList)ViewBag.SortByList, " ")
#Html.Label("PO #: ")
#Html.TextBox("poNumber")
#Html.Label("Freight #: ")
#Html.TextBox("freightNumber")
#Html.Label("Vendor Name: ")
#Html.TextBox("vendorName")
</p>
<p>
#Html.Label("Issue Date")
#Html.TextBox("beginIssueDate") - #Html.TextBox("endIssueDate")
#Html.Label("Invoice Date")
#Html.TextBox("beginInvoiceDate") - #Html.TextBox("endInvoiceDate")
#Html.Label("Completed Date")
#Html.TextBox("beginCompletedDate") - #Html.TextBox("endCompletedDate")
#Html.Label("Quick Filter: ")
#Html.TextBox("quickFilter")
</p>
<p>
<input type="submit" value="Go" />
<input type="button" value="Printable View" onclick=" location.href = '#Url.Action("PrintablePdf", "ApIssues")' " />
<input type="button" value="Add New Task" onclick=" location.href = '#Url.Action("Create", "ApIssues")' " />
<input type="button" value="Reporting" />
</p>
}
</div>
<div class="issue-table">
<h2>A/P Issues</h2>
<table id="data-table">
<tr>
<th style="border: 2px solid black; text-align: center; width: 12%">
#Html.ActionLink("Task ID", "Index",
new { sortOrder = "TaskID", CurrentSort = ViewBag.CurrentSort })
</th>
<th style="border: 2px solid black; text-align: center; width: 12%">
#Html.ActionLink("Task Date", "Index",
new { sortOrder = "TaskDate", CurrentSort = ViewBag.CurrentSort })
</th>
<th style="border: 2px solid black; text-align: center; width: 12%">
#Html.ActionLink("Invoice Date", "Index",
new { sortOrder = "InvDate", CurrentSort = ViewBag.CurrentSort })
</th>
<th style="border: 2px solid black; text-align: center; width: 12%">
#Html.ActionLink("Assigned To", "Index",
new { sortOrder = "AssignedTo", CurrentSort = ViewBag.CurrentSort })
</th>
<th style="border: 2px solid black; text-align: center; width: 12%">
#Html.ActionLink("CC", "Index",
new { sortOrder = "CC", CurrentSort = ViewBag.CurrentSort })
</th>
<th style="border: 2px solid black; text-align: center; width: 12%">
#Html.ActionLink("WHSE", "Index",
new { sortOrder = "Whse", CurrentSort = ViewBag.CurrentSort })
</th>
<th style="border: 2px solid black; text-align: center; width: 12%">
#Html.ActionLink("PO #", "Index",
new { sortOrder = "PO", CurrentSort = ViewBag.CurrentSort })
</th>
<th style="border: 2px solid black; text-align: center; width: 12%">
#Html.ActionLink("Freight #", "Index",
new { sortOrder = "FreightNo", CurrentSort = ViewBag.CurrentSort })
</th>
<th style="border: 2px solid black; text-align: center; width: 12%">
#Html.ActionLink("Vendor Name", "Index",
new { sortOrder = "VendName", CurrentSort = ViewBag.CurrentSort })
</th>
<th style="border: 2px solid black; text-align: center; width: 12%">
#Html.ActionLink("Req. Completion Date", "Index",
new { sortOrder = "ReqCompDate", CurrentSort = ViewBag.CurrentSort })
</th>
<th style="border: 2px solid black; text-align: center; width: 12%">
#Html.ActionLink("Task Type", "Index",
new { sortOrder = "TaskType", CurrentSort = ViewBag.CurrentSort })
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.ActionLink(item.TaskID.ToString(), "Task", new { id = item.TaskID })
</td>
<td>
#Html.DisplayFor(modelItem => item.TaskDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.InvDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.AssignedTo)
</td>
<td>
#Html.DisplayFor(modelItem => item.CC)
</td>
<td>
#Html.DisplayFor(modelItem => item.Whse)
</td>
<td>
#Html.DisplayFor(modelItem => item.PO)
</td>
<td>
#Html.DisplayFor(modelItem => item.FreightNo)
</td>
<td>
#Html.DisplayFor(modelItem => item.VendName)
</td>
<td>
#Html.DisplayFor(modelItem => item.ReqCompDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.TaskType)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.TaskID })
</td>
</tr>
}
</table>
<br />
<div id='Paging' style="text-align:center">
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber)
of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("Index", new {page}))
</div>
</div>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://sunnywalker.github.io/jQuery.FilterTable/jquery.filtertable.min.js"></script>
<script src="~/Scripts/Additional JS/jquery.tablesorter.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('table').filterTable(
{
minRows: 1,
label: "Search :",
inputSelector: "#quickFilter" ,
placeholder: "Keyword"
});
});
</script>
</head>
Here is my action:
public ActionResult Index(string sortOrder,string currentSort, int? page, string company, string warehouse,
string pastDue, string assignedToBy, string openco, string sortBy, string poNumber, string freightNumber,
string vendorName, string beginIssueDate, string endIssueDate, string beginInvoiceDate, string endInvoiceDate,
string beginCompletedDate, string endCompletedDate)
{
//Variable Definitions
const int pageSize = 20;
var pageIndex = 1;
pageIndex = page.HasValue ? Convert.ToInt32(page) : 1;
IPagedList<AP_Tasks> tasks = null;
// Instantiate the Entities
var nxtDb = new nxtSQLEntities();
var db = new Accounting_AaronTestEntities();
var usersDb = new PDDAEntities1();
//Query that gets the warehouses, companys, and users from the nxtDB and the PPP DB
var whses = from w in nxtDb.icsds select w.whse;
var coNames = from c in nxtDb.icsds select c.name;
var userDb = new PDDAEntities1();
var query1 = from u in userDb.Users where u.Cono == 1 select new { u.UserName, u.FirstName, u.LastName };
var query2 = from gm in userDb.GroupMembers
join ug in userDb.UserGroups on gm.GroupID equals ug.GroupID
join u in userDb.Users on gm.UserName equals u.UserName
where ug.GroupName == "AP Department" || ug.GroupName == "MIS"
orderby new { u.LastName, u.FirstName }
select new { UserName = u.UserName, FirstName = u.FirstName, LastName = u.LastName };
var query3 = query1.Concat(query2);
var users = new List<string> { };
users.AddRange(query3.Select(entry => entry.UserName));
//Dropdown lists being created and using a viewbag to setup and communication line between the the conroller and view
var warehouseList = new SelectList(whses);
ViewBag.WarehouseList = warehouseList;
var companyList = new SelectList(coNames);
ViewBag.CompanyList = companyList;
var pastDueList = new SelectList(new[]{"Yes", "No"});
ViewBag.PastDueList = pastDueList;
var usersList = new SelectList(users);
ViewBag.UsersList = usersList;
var openCompList = new SelectList(new[] { "Open", "Completed" });
ViewBag.OpenCompList = openCompList;
var sortByList = new SelectList(new[] { "Task ID", "Warehouse", "Assigned To", "PO Number", "Task Date" });
ViewBag.SortByList = sortByList;
tasks = GetFilteredSortedTasks(db,company, warehouse, pastDue, assignedToBy, openco, sortBy, poNumber,
freightNumber, vendorName, beginIssueDate, endIssueDate, beginInvoiceDate, endInvoiceDate,
beginCompletedDate, endCompletedDate).ToPagedList(pageIndex, pageSize);
return View(tasks);
}
Html.PagedListPager can take an additional parameter that is an expression that tells it how to generate the URL for the next page:
#Html.PagedListPager((IPagedList)ViewBag.OnePageOfItems, page => SomeMethodToGetUrlFor(page))
What you need to do basically is keep the current URL of the page (with all the appropriate querystring params for the filters and such) and add or update a page parameter. The "add or update" part makes this tricky, though: for example, you can't just tack on &page=N to the end of the URL as page may already be present in the querystring. I created a UrlHelper extension for just this purpose:
public static string ModifyQueryString(this UrlHelper helper, string url, NameValueCollection updates, IEnumerable<string> removes)
{
NameValueCollection query;
var request = helper.RequestContext.HttpContext.Request;
if (string.IsNullOrWhiteSpace(url))
{
url = request.Url.AbsolutePath;
query = HttpUtility.ParseQueryString(request.QueryString.ToString());
}
else
{
var urlParts = url.Split('?');
url = urlParts[0];
if (urlParts.Length > 1)
{
query = HttpUtility.ParseQueryString(urlParts[1]);
}
else
{
query = new NameValueCollection();
}
}
updates = updates ?? new NameValueCollection();
foreach (string key in updates.Keys)
{
query.Set(key, updates[key]);
}
removes = removes ?? new List<string>();
foreach (string param in removes)
{
query.Remove(param);
}
if (query.HasKeys())
{
return string.Format("{0}?{1}", url, query.ToString());
}
else
{
return url;
}
}
What this does is essentially let you pass in a NameValueCollection of parameters you want to add or update and/or a list of parameters you want to remove from the querystring. By default, it uses the current request URL, but if you pass in a URL it will do the transformation on that instead. Finally, it returns the modified URL back to the view.
I also added some additional methods to make working with this a little easier such as:
public static string UpdateQueryParam(this UrlHelper helper, string param, object value)
{
return ModifyQueryString(helper, new NameValueCollection { { param, value.ToString() } }, null);
}
public static string UpdateQueryParam(this UrlHelper helper, string url, string param, object value)
{
return ModifyQueryString(helper, url, new NameValueCollection { { param, value.ToString() } }, null);
}
So, if I just need to add/update one parameter, I don't need to actually instantiate a new NameValueCollection in my view.
Using these extensions, then, you can modify the URL appropriately with:
Url.UpdateQueryParam("page", page)
Which makes your pager line:
#Html.PagedListPager((IPagedList)ViewBag.OnePageOfItems, page => Url.UpdateQueryParam("page", page))
Here is my html part I want to choose and post a file to method in the server.
<div class="control-group">
<input type="hidden" name="id" data-bind="value: id" />
<div class="controls">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="fileupload-new thumbnail" style="width: 200px; height: 150px;">
<embed height="50" width="100" data-bind="attr: { src: mediaUrl() }" />
</div>
<div class="fileupload-preview fileupload-exists thumbnail" style="max-width: 200px; max-height: 150px; line-height: 20px;">
</div>
<div>
<span class="btn btn-file"><span class="fileupload-new">Choose a Audio/Voice</span> <span class="fileupload-exists">Change</span>
<input type="file" name="photoFile" class="default" />
</span><a data-bind="click: addMediaFile" href="#" class="btn fileupload-exists"
data-dismiss="fileupload">Save</a>
</div>
</div>
</div>
</div>
And here is addMediaFile javascript function in my ViewModel file
self.addMediaFile = function () {
utils.UIBlock();
$("#mediaForm").ajaxSubmit({
url: "api/Work/EditLibraryItemForMedia",
type: "POST",
success: function (result) {
self.mediaFilePath(result);
utils.UIUnBlock();
utils.showSuccess("Dosya kaydedilmiştir");
},
error: function () {
utils.UIUnBlock();
}
});
}
And finally here is my EditLibraryItemForMedia method in the server.
private Task<List<string>> UploadMediaFile()
{
string folderPath = ConfigurationManager.AppSettings["mediaFilesFolder"].ToString();
MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider(folderPath);
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
return Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(r => { return new List<string>(); });
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
}
string resizedImagesFolderPath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Images/UploadedMedias/"));
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
return Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(
readTask =>
{
MultipartFormDataStreamProvider provider = readTask.Result;
return provider.FileData.Select(fileData =>
{
string itemId = provider.FormData["id"];
FileInfo fileInfo = new FileInfo(itemId);
string mimeType = GetMimeType(fileData.Headers.ContentDisposition.FileName);
string extension = "";
if (mimeType == "audio/mpeg3" || mimeType == "audio/x-mpeg-3" || mimeType == "video/mpeg" || mimeType == "video/x-mpeg")
{
extension = ".mp3";
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
}
// Add extensions to files
string fileName = itemId + extension;
string filePath = Path.Combine(folderPath, fileName);
if (File.Exists(filePath))
{
File.Delete(filePath);
}
File.Move(fileData.LocalFileName, filePath);
WorkService.UpdateMediaFile(itemId, Path.GetFileName(filePath));
return fileName;
}).ToList();
});
}
Actually problem is that I can't upload an audio and video using this procedure.