Kendo UI Upload Async Error - file-upload

I downloaded a trial version of Kendo.UI, so logging onto the forums, at this stage is not possible, hoping someone on here can help me solve this problem.
I'm trying to implement the async upload onto a basic MVC 4 application. I've added a reference to the Kendo.UI.MVC wrappers, and added the necessary namespace Kendo.UI.MVC to both web.config files (root and under Views).
If I implement a basic uploader on my landing view (index.cshtml) it works fine:
<form action="/Home/Save" method="post">
#(Html.Kendo().Upload().Name("files"))
<input type="submit" value="Submit" />
</form>
However, as soon as I add the Save() method to Async, I get an "index was out of range" exception. I know it's the save method, because if I just add "AutoUpload(true)" without an action reference, it does not throw an exception. If I just add "Remove("Remove", "Home")" it still shows the Select button, without an error, but the "Save("Save", "Home")" method keeps throwing the mentioned exception.
I followed the examples that ship with the trial to the letter and it should web working, yet it does not.
View (index.cshtml):
#(Html.Kendo()
.Upload()
.Name("files")
.Async(async => async
.Save("Save", "Home")))
-- Error is being thrown on the above statement
#(Html.Kendo()
.Upload()
.Name("files")
.Async(async => async
.AutoUpload(true)))
-- this line works
Controller (HomeController):
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Save(IEnumerable<HttpPostedFile> files)
{
// I just want the break-point to be hit
// does not due to IndexOutOfRange exception being thrown
return Content("");
}
}

The only thing that seems wrong is the Razor syntax:
(#Html.Kendo()
should be
#(Html.Kendo()
I was able to run your code with this small change.

Updated the MVC templates for Visual Studio and it works. Thanks.

Related

Blazor Server Side, call JavaScript function that resides in a CDN from a .razor page when it renders

I'm trying to include Bootstrap for Material Design into my Blazor Server Side project. I have it working perfectly in a plain HTML file, but the issue with Blazor comes with a script. which I assume needs to run after a page was rendered. The script calls a function from a CDN.
<script src="https://unpkg.com/bootstrap-material-design#4.1.1/dist/js/bootstrap-material-design.js" integrity="sha384-CauSuKpEqAFajSpkdjv3z9t8E7RlpJ1UP0lKM/+NdtSarroVKu069AlsRPKkFBz9" crossorigin="anonymous"></script>
I have added the CDN in my tag on _Hostcshtml and have verified that it is correctly called when system is compiled.
The function in question (which does validation on form input fields) is
<script>$(document).ready(function() { $('body').bootstrapMaterialDesign(); });</script>
On the plain HTML file this call is just in the tag after the CDN call.
My problem is to correctly call the .bootstrapMaterialDesign in my OnAfterRenderAsync in Bootstrap.
Current code, which is obviously incorrect is:
#page "/signUpContak"
#layout SignUpLayout #inject IJSRuntime JSRuntime;
....
#code { protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) await JSRuntime.InvokeAsync<>("bootstrapMaterialDesign"); } }
I hope this makes sense. The implementation documentation for Bootstrap Material Design is at https://fezvrasta.github.io/bootstrap-material-design/docs/4.0/getting-started/introduction/
I managed to fix the issue by doing the below.
In my _host.cshtml I added:
function InitializeBootstrapMaterialDesign() {
$(document).ready(function ()
{$('body').bootstrapMaterialDesign(); });
}
And on SignUpContak.razor I added:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await JSRuntime.InvokeVoidAsync("InitializeBootstrapMaterialDesign");
}

How to sign out over HttpContext in server-side Blazor

I access the HttpContext in a Blazor server-side view to manually log out. I added this line to Startup.cs: services.AddHttpContextAccessor(); and inject it in the view with #inject IHttpContextAccessor HttpContextAccessor.
I've got a log out button which tries to execute this code:
await HttpContextAccessor.HttpContext.SignOutAsync("Cookies");
but I get the following error message:
System.InvalidOperationException: 'Headers are read-only, response has already started.'
How can I prevent this error?
If you scaffolded Identity and overridden the old "LogOut.cshtml" from when you created the project via template, the Logout button won't logout. Assume you've used the default IdentityUser model. I ran into this issue and just wanted to add this if anyone else had this problem as well. I'm using Blazor Server with .Net 5.0.3's template. You can remove the Logout.cshtml.cs after as well.
Replace this \Areas\Identity\Pages\Account\LogOut.cshtml
#page
#model LogoutModel
#{
ViewData["Title"] = "Log out";
}
<header>
<h1>#ViewData["Title"]</h1>
#{
if (User.Identity.IsAuthenticated)
{
<form class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="#Url.Page("/", new { area = "" })" method="post">
<button type="submit" class="nav-link btn btn-link text-dark">Click here to Logout</button>
</form>
}
else
{
<p>You have successfully logged out of the application.</p>
}
}
</header>
Replace with
#page
#using Microsoft.AspNetCore.Identity
#attribute [IgnoreAntiforgeryToken]
#inject SignInManager<IdentityUser> SignInManager
#functions {
public async Task<IActionResult> OnPost()
{
if (SignInManager.IsSignedIn(User))
{
await SignInManager.SignOutAsync();
}
return Redirect("~/");
}
}
This tripped me up too, but you need the logout functionality to be on a Razor Page (not a Blazor component). Create a Logout page and put your logout code in the OnGetAsync() method.
Your logout button can then link to the logout page.
http://lightswitchhelpwebsite.com/Blog/tabid/61/EntryId/4316/A-Demonstration-of-Simple-Server-side-Blazor-Cookie-Authentication.aspx - this is a helpful example
Don't use IHttpContextAccessor.
I guess that you're using ASP.NET Core Blazor authentication and authorization new system. If not, then start with it right now. Live is too short to be wasted over other things. This is the best product created so far for Blazor's authentication and authorization, and it is based on the Identity UI (This is not Blazor, of course). Additionally, there are a couple of Components which enable controlling the flow of authentication and authorization in your application, such as displaying a "Log in" button and a "Log out" button in your layout, interchangeably altering depending on your authentication state, etc.
Please, go to this page and start learning this excellent system, and then come here for specific issues you face:
https://learn.microsoft.com/en-us/aspnet/core/security/blazor/?view=aspnetcore-3.0&tabs=visual-studio
Hope this helps...

Handle Razor Page Exception

Hi I'm getting strange behavior in our AspNetCore 2.1 application using Razor Pages. When an exception escapes from a Razor Page action like OnGet the application crashes. The exception never reaches any middleware. It looks like the application seems is crashing somewhere in the internal PageActionInvoker.Next method.
I can't paste the code as it far too much. But the following will crash the application:
public async void OnGet() {
await Task.CompletedTask; // normally we await something else
throw new Exception("Boom!");
}
Note:
We are:
combining Views and Razor Pages. The Views are part of the 'older' section of the application.
we are allowing Razor Page area's.
Do we have to configure some feature?
Are we missing something? Does someone have suggestions?
FOUND IT
Nothing special. Well AspNetCore accepts async void OnGet and everything works fine UNTIL an exception is raised.
using the following fixed it.
public async Task OnGetAsync() {
It seems that even AspNetCore doesn't handle the following construction well:
public async void OnGet() {
...
}
Even though it's accepted and seems to be working possible exceptions are not handled correctly.
The correct way to do this is:
public async Task OnGetAsync() {
....
}
Don't know whether this classifies as a AspNetCore bug ... in that sense maybe it should be rejected like many other things. Oh well ... bug fixed.

Combining conventional routing and attribute routing in asp.net core

I've tried to combine conventional and attribute routing together.
However it doesn't work as expected, probably because I've missed to do something.
What I have so far:
Routing:
builder.MapRoute("Default", "{controller=Home}/{action=Index}/{id?}");
Home Controller:
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
Attribute Mapped Controller:
[Route("Admin")]
public class AdminLockController : Controller
{
[Route("ControlCenter")]
public async Task<IActionResult> Index()
{
return View();
}
}
_Layout.cshtml
<a asp-controller="Home" asp-action="Index">
<img id="app-logo-image" src="/img/corporate_logo.png"/>
</a>
Now when when the view Home\Index.cshtml get rendered the link in _Layout.cshtml will become
(Correct).
But when the view AdminLock\Index.cshtml get rendere the link is (Wrong).
So I guess I need to do some extra configuration, but no idea what. Any hints?
UPDATE 1:
It works perfectly in a new created mvc project. So it has to be something wrong in my project... i will try to find out what the issue is...
Found the Issue.
I'm using the Smidge as a bundler and Minifier.
I registred the Smidge Middleware before the Mvc Middleware. That seems to mess up the routing. I opened an Issue on githup. See https://github.com/Shazwazza/Smidge/issues/71
Changing the order fixes the problem.

kendo ui editorfor imagebrowser returns 403

I'm new to web development and I'm trying to implement the Kendo UI editor with an image browser to insert into the document on an MVC 4.5 page. the editor is working fine, however, when i click the insert image button i gt a 403 forbidden popup message.
I've created a custom image browser controller pointing to ~/Content/images.
and in my view, i am using the custom browser controller within my code
#(Html.Kendo().EditorFor(m => m.QuestionText)
.Encode(false)
.HtmlAttributes(new { style = "width: 100%; height: 200px" })
.Name("EditQuestionText")
.Tools(tools => tools.Clear().InsertImage())
.ImageBrowser(imageBrowser => imageBrowser
.Image("~/JFA/QuestionImages/{0}")
.Read("Read", "JFAImageBrowser"))
)
I've compared my code to the sample project from Kendo for the EditorFor (which will browse the folder) but can find no discernible differences... I also cannot find much in the way of other people who are having this problem so i suspect there is a setting that i cannot find that is causing my issue, any help would be GREATLY appreicated
my image browser (taken directly from the demo)
public class JFAImageBrowserController : EditorImageBrowserController
{
private const string contentFolderRoot = "~/Content/images";
public override string ContentPath
{
get
{
return contentFolderRoot;
}
}
additionally, using Fiddler the click event for the "Insert Image" button is
GET /JFA/JFAImageBrowser/Read?path=%2F HTTP/1.1
where as the demo is
POST /ImageBrowser/Read HTTP/1.1
I don't know why the demo is using a POST where as mine is using a GET, unless this is because of the overridden image browswer
That code looks fine. Can you make sure your JFAImageBrowser controller looks something like this?
public class BlogImagesController : EditorImageBrowserController
{
//
// GET: /BlogImage/
public ActionResult Index()
{
return View();
}
public override string ContentPath
{
get { return AssetFilePaths.BlogContentPath; }
}
}
It's important that it inherits from EditorImageBrowserController
Also, a 403 may mean that the user doesn't have permission to access the directory. Check the permissions for the user you're running as.
It turns out my problem was in the _Layout page. I was using bundling and either
A) I made some error when setting up the bundling
-or-
b) the bundling didn't work as expected/intended.
either way i added the individual script/java script references and it works as expected.
Here is the solution to this problem
the page this issue fixed was it kendo forum
http://www.telerik.com/forums/implementing-image-browser-for-editor
and the direct link for the demo
http://www.telerik.com/clientsfiles/e3e38f54-7bb7-4bec-b637-7c30c7841dd1_KendoEditorImageBrowser.zip?sfvrsn=0
and if this demo didn't work you can see this sample i made from above
https://www.mediafire.com/?9hy728ht4cnevxt
you can browse the editor through HomeController and the action name is homepage (home/homepage)
& I think that the error was in different uses of paths between the base controller & child controller you make.