Why is my image not displaying ? cshtml - c#

I'm trying to display an image and I don't understand where my error is. I checked questions on the topic, but without result.
I've got an image in a byte[] type object : imageBuffer. I'm sure the everything is ok till here, the following code is functioning.
unsafe
{
fixed (byte* ptr = imageBuffer)
{
using (Bitmap image = new Bitmap(20 * lengthList, 20 * lengthList, 20 * lengthList * 4,
PixelFormat.Format32bppRgb, new IntPtr(ptr)))
{
image.Save(#"C:\Users\FS091843\Desktop\ Stations\Station1\greyscale.png");
}
}
}
(PS : my imageBuffer object has before the Bitmap creation no dimensions (I mean, it is no 2D array) : it is more precisely a byte[400 * lengthList * lengthList * 4])
As the convertbase64() can't figure out the dimensions without indications, I tried this :
// Some stuff before
DashboardPageModel dashboard = new DashboardPageModel();
unsafe
{
fixed (byte* ptr = imageBuffer)
{
using (Bitmap image = new Bitmap(20 * lengthList, 20 * lengthList, 20 * lengthList * 4,
PixelFormat.Format32bppRgb, new IntPtr(ptr)))
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
image.Save(#"C:\Users\FS091843\Desktop\Stations\Station1\greyscale.png");
dashboard.image = imageBytes;
// Convert byte[] to Base64 String
}
}
}
}
return View(MVC.Views.Common.Dashboard.DashboardIndex, dashboard);
Where dashboard comes from my Model class (my project is an MVC project).
My View file finally looks like :
#model Serene7.Common.DashboardPageModel
#{
ViewData["Title"] = "Dashboard";
ViewData["PageId"] = "Dashboard";
}
#section Head {
<link rel="stylesheet" href="~/Content/iCheck/flat/blue.css">
<link rel="stylesheet" href="~/Scripts/morris/morris.css">
<link rel="stylesheet" href="~/Scripts/jvectormap/jquery-jvectormap-1.2.2.css">
<link rel="stylesheet" href="~/Scripts/datepicker/datepicker3.css">
<link rel="stylesheet" href="~/Scripts/daterangepicker/daterangepicker-bs3.css">
<link rel="stylesheet" href="~/Scripts/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css">
<script src="~/Scripts/raphael/raphael-min.js"></script>
<script src="~/Scripts/morris/morris.min.js"></script>
<script src="~/Scripts/sparkline/jquery.sparkline.min.js"></script>
<script src="~/Scripts/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
<script src="~/Scripts/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
<script src="~/Scripts/knob/jquery.knob.js"></script>
<script src="~/Scripts/daterangepicker/moment.min.js"></script>
<script src="~/Scripts/daterangepicker/daterangepicker.js"></script>
<script src="~/Scripts/datepicker/bootstrap-datepicker.js"></script>
<script src="~/Scripts/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
<script src="~/Scripts/adminlte/pages/dashboard.js"></script>
<script src="~/Scripts/adminlte/demo.js"></script>
}
#section ContentHeader {
<h1>#LocalText.Get("Navigation.Dashboard")<small>#Html.Raw(Texts.Site.Dashboard.ContentDescription)</small></h1>
}
<!-- Small boxes (Stat box) -->
<div class="row">...</div><!-- /.row -->
<!-- Main row -->
<img src="data:image/png;base64,#(Convert.ToBase64String(Model.image))" alt="Red dot"/><!-- not really a red dot, had no idea what to enter as description -->
<div class="row">...</div>
and I get as a result :
Why isn't it functioning ?
Here is the html output
//<head>...</head>
<body id="s-LoginPage" class="no-navigation">
<script id="Template_Membership_LoginPanel" type="text/template">
<div class="flex-layout">
<div class="logo"></div>
<h3>Welcome to SERENE (Serenity Application Template)</h3>
<form id="~_Form" action="">
<div class="s-Form">
<div class="fieldset ui-widget ui-widget-content ui-corner-all">
<div id="~_PropertyGrid"></div>
<div class="clear"></div>
</div>
<div class="buttons">
<button id="~_LoginButton" type="submit" class="btn btn-primary">
Sign In
</button>
</div>
<div class="actions">
<i class="fa fa-angle-right"></i> Forgot password?
<i class="fa fa-angle-right"></i> Register a new account
<div class="clear"></div>
</div>
</div>
</form>
</div>
</script>
<div class="page-content">
<div id="LoginPanel">
</div>
</div>
<script type="text/javascript">
jQuery(function() {
new Serene7.Membership.LoginPanel($('#LoginPanel')).init();
});
</script>
</body>
</html>
The image looks like :

// …
using (MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
// …
You are storing raw bytes in the memory stream. It is just by chance that your image viewing tool displays the file properly because most image viewers are built to (mostly) ignore file extensions and try to render whatever is appropriate for them.
You need to actually convert your image into a PNG file in order to get the actual PNG bytes out of it:
// …
using (MemoryStream m = new MemoryStream())
{
image.Save(m, ImageFormat.Png); // convert to PNG
byte[] imageBytes = m.ToArray();
// …
Once you did that, the bytes will be proper PNG data, so it should also render in the browser properly, and the file on your disk should become a lot smaller since it’s no longer raw bitmap data.

Related

How To render HTML with CSHTML Template file in razor with enabled static File

Hello I am actually generating a html file from cshtml template for reporting purpose.
The issue is when i use cdn link for bootstrap in the cshtml file the html rendered got all the css i designed but when using a local access of bootstrap it the style is not rendered at all its also the same thing when trying to render images from local file.
Here is the code for generating the html file:
var httpContex = new DefaultHttpContext
{
RequestServices=_serviceProvider
};
var actionContext = new ActionContext(httpContex, new RouteData(), new ActionDescriptor());
await using var outputWriter = new StringWriter();
var viewResutl = _viewEngine.FindView(actionContext, templateFileName, false);
var viewDictionnary = new ViewDataDictionary<TViewModel>(new EmptyModelMetadataProvider(), new ModelStateDictionary())
{
Model = viewModel
};
var tempDataDictionnary = new TempDataDictionary(httpContex, _tempDataProvider);
if (!viewResutl.Success)
{
throw new KeyNotFoundException($"could not render the HTML,because {templateFileName} template does not exist");
}
try
{
var viewContext = new ViewContext(actionContext, viewResutl.View, viewDictionnary, tempDataDictionnary, outputWriter, new HtmlHelperOptions());
await viewResutl.View.RenderAsync(viewContext);
return outputWriter.ToString();
}
catch(Exception ex)
{
_logger.LogError(ex, "Could not render the HTML because of an error");
return string.Empty;
}
Here is part of the cshtml file :
#model XXXXXReporter.ViewModels.XXXXXModel
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>#Model.title</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>
<link rel="stylesheet" href="~/StaticFiles/bootstrap.min.css"/>
</head>
<body style="min-height:100vh">
<div class="container-fluid" >
<div class="row">
<div class="col">
<h2 class="text-center">XXXX Advanced Reporting System</h2>
</div>
<div class="col">
<img src="~/XXXXlogo.png" alt="ANY IMAGE" />
</div>
</div >
<div class="row border border-info border-2 rounded bg-info" style="margin-top: 200px;">
<h3 class="text-center text-white">General Availabilty And Sensor Status[PRTG]</h3>
</div>
<div class="row " style="margin-top: 200px;">
<p>Period Time:<span>All Period</span></p>
<p>Report By:<span>XXXX</span></p>
<p>Creation Date:<span>#DateTime.Now</span></p>
</div>
<div class="row" style="margin-top: 430px;">
#foreach (var elem in Model.panelList)
{
#Html.Raw(elem)
}
</div>
</body>
</html>
This line of code <link rel="stylesheet" href="~/StaticFiles/bootstrap.min.css"/> is never generated when the html is rendered (by commenting the cdn link above it)
The project is a .net Core Web API i have overiden the use of static file using this code in startup.cs:
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, #"StaticFiles")),
RequestPath = "/StaticFiles"
});
As stated in my previous question bootstrap and css not working with .net core api i think the problem is with the way razor render the html.
Is there a way to make it render the static file I pass in the cshtml file?or is there a correct way to generate html from a template using .net core API?
Regards,
Thanks for all your answer.
It was caused by puppeteersharp who was unable to serve the static file.
For the CSS i am using await page.AddStyleTagAsync(new AddTagOptions { Path = "StaticFiles/bootstrap.min.css" }); to inject the css to the page.
For the static image I am encoding it to base64 to make it displayable from there.

Cannot Use #Html.React in Layout Razor View File

It appears that after solving my previous issue with CSS, I've come into another roadblock. I was trying to do the "Optimization: Server-side rendering" exercise from the reactjs.net website. Unfortunately, problem - I can't use the "#Html.React" method in the razor view to pass the Comment Box model. I've tried several what were probably unnecessary imports, and ensuring that my ReactConfig file was updated so that I could use that code. Can anyone tell me what I'm missing here?
ReactConfig.cs:
using React;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(ReactExamplePractice.ReactConfig), "Configure")]
namespace ReactExamplePractice
{
using React;
public static class ReactConfig
{
public static void Configure()
{
// If you want to use server-side rendering of React components,
// add all the necessary JavaScript files here. This includes
// your components as well as all of their dependencies.
// See http://reactjs.net/ for more information. Example:
//ReactSiteConfiguration.Configuration
// .AddScript("~/Scripts/First.jsx")
// .AddScript("~/Scripts/Second.jsx");
ReactSiteConfiguration.Configuration = new ReactSiteConfiguration()
.AddScript("~/Scripts/react/Tutorial.jsx");
//ReactSiteConfiguration.Configuration
// //.AddScript("~/js/remarkable.min.js")
// .AddScript("~/Scripts/react/Tutorial.jsx");
// If you use an external build too (for example, Babel, Webpack,
// Browserify or Gulp), you can improve performance by disabling
// ReactJS.NET's version of Babel and loading the pre-transpiled
// scripts. Example:
//ReactSiteConfiguration.Configuration
// .SetLoadBabel(false)
// .AddScriptWithoutTransform("~/Scripts/bundle.server.js")
}
}
}
BundleConfig.cs:
using System.Web;
using System.Web.Optimization;
using System.Web.Optimization.React;
namespace ReactExamplePractice
{
public class BundleConfig
{
// For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new BabelBundle("~/bundles/main").Include(
"~/Scripts/react/Tutorial.jsx"
));
// Forces files to be combined and minified in debug mode
// Only used here to demonstrate how combination/minification works
// Normally you would use unminified versions in debug mode.
BundleTable.EnableOptimizations = true;
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
_Layout.cshtml:
#using System.Web.Optimization.React;
#using React;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
#*<environment exclude="Development">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</environment>*#
<environment exclude="Development">
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
</environment>
<title>#ViewData["Title"] - ASP.NET Core Pages Webpack</title>
#model IEnumerable<ReactExamplePractice.Models.CommentModel>
#{
Layout = null;
}
</head>
<body>
<div class="container">
<nav class="bg-dark mb-4 navbar navbar-dark navbar-expand-md">
<a asp-page="/Index" class="navbar-brand">
<em>ASP.NET Core Pages Webpack</em>
</a>
<button aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler" data-target="#topNavbarCollapse" data-toggle="collapse" type="button">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="topNavbarCollapse">
<ul class="mr-auto navbar-nav">
<li class="nav-item">
#Html.ActionLink("Application Name", "Index", "Default", new { area = "" }, new { #class = "navbar-brand" })
</li>
<li class="nav-item">
<a asp-page="/About" class="nav-link">About</a>
</li>
<li class="nav-item">
<a asp-page="/Contact" class="nav-link">Contact</a>
</li>
</ul>
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="https://twitter.com/damien_bod">
<img height="30" src="assets/damienbod.jpg" />
</a>
</li>
</ul>
</div>
</nav>
</div>
<partial name="_CookieConsentPartial" />
<div class="container body-content">
#RenderBody()
<hr />
<footer>
<p>© 2018 - ASP.NET Core Pages Webpack Bootstrap 4</p>
</footer>
</div>
<environment exclude="Development">
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
#*<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>*#
<script src="~/Scripts/jquery-3.3.1.slim.min.js"></script>
<script src="~/Scripts/popper.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/remarkable/1.7.1/remarkable.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.js"></script>
#Scripts.Render("~/bundles/main");
#*<script src="#Url.Content("~/Scripts/react/Tutorial.jsx")"></script>*#
</environment>
#RenderSection("Scripts", required: false)
</body>
</html>
DefaultController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using ReactExamplePractice.Models;
using System.Web.Optimization.React;
using React;
namespace ReactExamplePractice.Controllers
{
public class DefaultController : Controller
{
private static readonly IList<CommentModel> _comments;
static DefaultController()
{
_comments = new List<CommentModel>
{
new CommentModel
{
Id = 1,
Author = "Daniel Lo Nigro",
Text = "Hello ReactJS.NET World!"
},
new CommentModel
{
Id = 2,
Author = "Pete Hunt",
Text = "This is one comment"
},
new CommentModel
{
Id = 3,
Author = "Jordan Walke",
Text = "This is *another* comment"
},
};
}
[OutputCache(Location = OutputCacheLocation.None)]
public ActionResult Comments()
{
return Json(_comments, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult AddComment(CommentModel comment)
{
//Create a fake ID for this comment or something
comment.Id = _comments.Count + 1;
_comments.Add(comment);
return Content("Success :)");
}
// GET: Default
public ActionResult Index()
{
return View();
}
}
}
Tutorial.jsx:
class CommentBox extends React.Component {
constructor(props) {
super(props);
this.state = { data: this.props.initialData };
this.handleCommentSubmit = this.handleCommentSubmit.bind(this);
}
loadCommentsFromServer() {
const xhr = new XMLHttpRequest();
xhr.open('get', this.props.url, true);
xhr.onload = () => {
const data = JSON.parse(xhr.responseText);
this.setState({ data: data });
};
xhr.send();
}
handleCommentSubmit(comment) {
const comments = this.state.data;
// Optimistically set an id on the new comment. It will be replaced by an
// use a more robust system for ID generation.
// id generated by the server. In a production application you would likely
comment.Id = comments.length + 1;
const newComments = comments.concat([comment]);
this.setState({data: newComments});
const data = new FormData();
data.append('Author', comment.Author);
data.append('Text', comment.Text);
const xhr = new XMLHttpRequest();
xhr.open('post', this.props.submitUrl, true);
xhr.onload = () => this.loadCommentsFromServer();
xhr.send(data);
}
componentDidMount() {
window.setInterval(() => this.loadCommentsFromServer(), this.props.pollInterval);
}
render() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm onCommentSubmit={this.handleCommentSubmit} />
</div>
);
}
}
class CommentList extends React.Component {
render() {
const commentNodes = this.props.data.map(comment => (
<Comment author={comment.Author} key={comment.Id}>
{comment.Text}
</Comment>
));
return (
<div className="commentList">
{commentNodes}
</div>
);
}
}
class CommentForm extends React.Component {
constructor(props) {
super(props);
this.state = { author: '', text: '' };
this.handleAuthorChange = this.handleAuthorChange.bind(this);
this.handleTextChange = this.handleTextChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleAuthorChange(e) {
this.setState({author: e.target.value});
}
handleTextChange(e) {
this.setState({ text: e.target.value });
}
handleSubmit(e) {
e.preventDefault();
const author = this.state.author.trim();
const text = this.state.text.trim();
if (!text || !author) {
return;
}
this.props.onCommentSubmit({Author: author, Text: text});
this.setState({ author: '', text: '' });
}
render() {
return (
<form className="commentForm" onSubmit={this.handleSubmit} >
<input type="text" placeholder="Your name" value={this.state.author} onChange={this.handleAuthorChange} />
<input type="text" placeholder="Post something here!" value={this.state.text} onChange={this.handleTextChange} />
<input type="submit" value="Post" />
</form>
);
}
}
class Comment extends React.Component {
rawMarkup() {
const md = new (global.Remarkable || window.Remarkable)();
const rawMarkup = md.render(this.props.children.toString());
return { __html: rawMarkup };
}
render() {
return (
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
<span dangerouslySetInnerHTML={this.rawMarkup()} />
</div>
);
}
}
class HelloWorld extends React.Component {
render() {
return (
<div>
<h1> Hello World React JS! </h1>
</div>)
}
}
//ReactDOM.render(
// <CommentBox url="/comments" submitUrl="/comments/new" pollInterval={2000} />,
// document.getElementById('content')
//);
Any help/insight on this would be greatly appreciated. Thanks a ton in advance!
So, I've come to discover something odd, and maybe it's just my Visual Studio environment or something else, but when using the Html.React library from the NuGet package, it would fail to load the methods at first - but then, as soon as I saved the project, exited, and opened back up, this intellisense glitch disappeared!
I also want to mention quickly that there is a bug in the Remarkable library in the ASP.NET tutorial online. See the following post:
https://github.com/reactjs/React.NET/issues/349
I believe there is a workaround in there for this bug as well, whoever needs it.
This scenario was a strange one. I hope this post helps someone else down the road.

Fineuploader and Razor

I'm trying to upload an image with Fineuploader processing it with Razor (not MVC).
The error I get is:
Error when Attempting to parse XHR response text (Unexpected token {).
The code is this:
test.cshtml
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<link href="assets/fine-uploader.css" rel="stylesheet">
<link href="fineuploader-4.2.2.min.css" rel="stylesheet">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="jquery.fineuploader-4.2.2.js"></script>
<script src="jquery.fineuploader-4.2.2.min.js"></script>
</head>
<body>
<div id="fine-uploader"></div>
<script src="assets/fine-uploader.js"></script>
<script type="text/template" id="qq-template">
<div class="qq-uploader-selector qq-uploader">
<div class="qq-total-progress-bar-container-selector qq-total-progress-bar-container">
<div class="qq-total-progress-bar-selector qq-progress-bar qq-total-progress-bar"></div>
</div>
<div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>
<span>Drop files here to upload</span>
</div>
<div class="qq-upload-button-selector qq-upload-button">
<div>Upload a file</div>
</div>
<span class="qq-drop-processing-selector qq-drop-processing">
<span>Processing dropped files...</span>
<span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span>
</span>
<ul class="qq-upload-list-selector qq-upload-list">
<li>
<div class="qq-progress-bar-container-selector">
<div class="qq-progress-bar-selector qq-progress-bar"></div>
</div>
<span class="qq-upload-spinner-selector qq-upload-spinner"></span>
<span class="qq-edit-filename-icon-selector qq-edit-filename-icon"></span>
<span class="qq-upload-file-selector qq-upload-file"></span>
<input class="qq-edit-filename-selector qq-edit-filename" tabindex="0" type="text">
<span class="qq-upload-size-selector qq-upload-size"></span>
<a class="qq-upload-cancel-selector qq-upload-cancel" href="#">Cancel</a>
<a class="qq-upload-retry-selector qq-upload-retry" href="#">Retry</a>
<a class="qq-upload-delete-selector qq-upload-delete" href="#">Delete</a>
<span class="qq-upload-status-text-selector qq-upload-status-text"></span>
</li>
</ul>
</div>
</script>
</body>
</html>
fine-uploader.js
function createUploader() {
var uploader = new qq.FineUploader({
// Pass the HTML element here
// element: document.getElementById('fine-uploader'),
// or, if using jQuery
element: $('#fine-uploader')[0],
// Use the relevant server script url here
// if it's different from the default “/server/upload”
text: {
uploadButton: 'SELEZIONA FILE'
},
request: {
`enter code here` multiple: false,
validation: {
sizeLimit: 2147483648 //2GB
},
endpoint: 'FileUpload.cshtml',
forceMultipart: false,
customHeaders: { Accept: 'application/json' },
debug: true,
//
callbacks: {
onComplete: function (id, fileName, responseJSON) {
if (responseJSON.success) {
$('#imgPreview').html('<img src="~/Scripts/fineuploader/upload/' + filename + '" alt="' + filename + '">');
}
}
}
//
}
});
}
FineUpload.cshtml
#{
if(IsPost) {
var file = Request.Files[0];
var fileName = Path.GetFileName(file.FileName);
var rootPath = Server.MapPath("~/Scripts/fineuploader/upload/");
file.SaveAs(Path.Combine(rootPath, fileName));
// Json.Write(fileSavePath, Response.Output);
var json = Html.Raw(Json.Encode(new { link = #"~/Scripts/fineuploader/upload/" + fileName}));
//Response.ContentType = "text/plain";
Response.Write(json);
Response.ContentType = "application/json";
Response.Write("{\"success\":true}");
Response.End();
}
}

JQWidgets not working in MVC 4

I am trying to use the sample off of jqWidgets for the ListBox. I have copied the code directly into my index.cshtml file. I am not seeing the desired results, which would be what the sample looks like. All it is showing me is the button.
Here is a link to the page. I have reduced the content and allowed for anyone to look at it: https://drive.azurewebsites.net/Question
Here is the sample's website: http://www.jqwidgets.com/jquery-widgets-documentation/documentation/jqxlistbox/jquery-listbox-getting-started.htm
I'm not sure how to troubleshoot this or where to look to see what is really going wrong. I am using Chrome and pulled up Inspect Element. The scripts are being retrieved.
Here is my code:
<link rel="stylesheet" href="~/Scripts/jqwidgets/styles/jqx.base.css" type="text/css" />
<script type="text/javascript" src="~/Scripts/jqwidgets/jqxcore.js"></script><script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="~/Scripts/jqwidgets/jqxbuttons.js"></script>
<script type="text/javascript" src="~/Scripts/jqwidgets/jqxscrollbar.js"></script>
<script type="text/javascript" src="~/Scripts/jqwidgets/jqxlistbox.js"></script>
<body>
<div id='content'>
<script type="text/javascript">
$(document).ready(function () {
var source = [
"Affogato",
"Americano",
"Bicerin",
"Breve",
"Café Bombón",
"Café au lait",
"Caffé Corretto",
"Café Crema",
"Caffé Latte",
];
// Create a jqxListBox
$("#jqxlistbox").jqxListBox({ source: source, width: '200px', height: '200px' });
// disable the sixth item.
$("#jqxlistbox").jqxListBox('disableAt', 5);
// bind to 'select' event.
$('#jqxlistbox').bind('select', function (event) {
var args = event.args;
var item = $('#jqxlistbox').jqxListBox('getItem', args.index);
$("#eventlog").html('Selected: ' + item.label);
});
$("#button").jqxButton();
$("#button").click(function () {
var item = $('#jqxlistbox').jqxListBox('getSelectedItem');
if (item != null) {
alert(item.label);
}
});
});
</script>
<div id='jqxlistbox'>
</div>
<div style="margin-top: 10px;">
<input id="button" type="button" value="Get Selected Item" />
<div id="eventlog"></div>
</div>
</div>
</body>
Your Scripts are not referenced correctly. In MVC4, the process of referencing Scripts is different - http://www.jqwidgets.com/jquery-widgets-documentation/documentation/asp.net-integration/asp.net-binding-to-sql-database-mvc4.htm

.NET MVC - Return video file for jPlayer

I have two methods and first one returns a video file, the other one returns thumbnail image.
public ActionResult Video(string id)
{
UserVideo videoEntity = AccountBasicEntity.GetUserVideoWithID(id);
string videoPath = ConfigurationManager.AppSettings["VideoPath"] + videoEntity.VideoFileName;
return File(videoPath, "video/mp4");
}
public ActionResult Thumb(string id)
{
UserVideo videoEntity = AccountBasicEntity.GetUserVideoWithID(id);
string thumbPath = ConfigurationManager.AppSettings["ThumbsPath"] + videoEntity.PreviewImageFileName;
return File(thumbPath, "image/jpg");
}
and I can reach the urls as
http://localhost/media/video/GTt-b2DcEG ( returns video file )
http://localhost/media/thumb/GTt-b2DcEG ( returns image file )
The method works fine which returns image file. But the other one doesn't work, browser (chrome) doesn't play or jPlayer doesn't play the video file But browser or jplayer shows the thumbnail image. I debugged and paths are ok.
Video path is : C:\Web\data\videos\GTt-b2DcEG.mp4
Image path is : C:\Web\data\thumbs\GTt-b2DcEG.jpg
Do I miss something ? what is the best way to feed a ajax-based video player in this situation?
Thanks.
Client side :
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<!-- Website Design By: www.happyworm.com -->
<title>Demo : jPlayer as a video player</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link href="skin/pink.flag/jplayer.pink.flag.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.jplayer.min.js"></script>
<script type="text/javascript">
//<![CDATA[
$(document).ready(function(){
$("#jquery_jplayer_1").jPlayer({
ready: function () {
$(this).jPlayer("setMedia", {
m4v: "http://localhost/media/video/GTt-b2DcEG",
poster: "http://localhost/media/thumb/GTt-b2DcEG"
});
},
swfPath: "js",
supplied: "webmv, ogv, m4v",
size: {
width: "640px",
height: "360px",
cssClass: "jp-video-360p"
}
});
});
//]]>
</script>
</head>
<body>
<div id="jp_container_1" class="jp-video jp-video-360p">
<div class="jp-type-single">
<div id="jquery_jplayer_1" class="jp-jplayer"></div>
<div class="jp-gui">
<div class="jp-video-play">
play
</div>
<div class="jp-interface">
<div class="jp-progress">
<div class="jp-seek-bar">
<div class="jp-play-bar"></div>
</div>
</div>
<div class="jp-current-time"></div>
<div class="jp-duration"></div>
<div class="jp-title">
<ul>
<li>Big Buck Bunny Trailer</li>
</ul>
</div>
<div class="jp-controls-holder">
<ul class="jp-controls">
<li>play</li>
<li>pause</li>
<li>stop</li>
<li>mute</li>
<li>unmute</li>
<li>max volume</li>
</ul>
<div class="jp-volume-bar">
<div class="jp-volume-bar-value"></div>
</div>
<ul class="jp-toggles">
<li>full screen</li>
<li>restore screen</li>
<li>repeat</li>
<li>repeat off</li>
</ul>
</div>
</div>
</div>
<div class="jp-no-solution">
<span>Update Required</span>
To play the media you will need to either update your browser to a recent version or update your Flash plugin.
</div>
</div>
</div>
</body>
</html>
You didn't mention what troubleshooting you had already done.
When I've had this issue in the past, the first thing I check is that you have added the mime type in IIS. By default, IIS 6 & 7 won't serve up content for mime types that are not configured.
How to add mime types with IIS7 Web.config
Next would be that the codec used to encode the mp4 is playable by the jPlayer.
jPlayer Media Encoding

Categories

Resources