Have searched for solutions and also tried different things but unable to find solution for this one. So my question is:
I have a form with fields like name,email,contact no for registration. Once i click on the button what i am doing is that i am allowing user to download a file for which i have written the code as below
[HttpPost]
public ActionResult MBA_Programme(mba_programmeViewModel vm)
{
if (vm.mba_Id == null || vm.mba_Id == 0)
{
vm.Created_Date = DateTime.Now;
vm.Created_By = User.Identity.Name.ToString();
admin.addMbaDetail(vm);
if (vm.Flag != null)
{
ModelState.Clear();
return new FilePathResult(Server.MapPath("~/eiclandingpages/EIC-MBA.doc"), "application/msword");
}
else
{
return RedirectToAction("MBA_Programme", "EIC");
}
}
else
{
return RedirectToAction("MBA_Programme", "EIC");
}
}
The issue which i am facing is that once the form is getting downloaded the page is not getting refresh . I tried modelstate.clear() but not able to do it . I tried jquery also for location.reload but it refreshes but file wont downlaod and also refresh with delay.
Kindly help.
p.s: file i am getting from the folder in the project
Related
I use this code for multiple upload with jQuery ajax in ASP.NET MVC:
public ActionResult GetFiles(HttpPostedFileBase NewsFilePath)
{
if (NewsFilePath != null)
{
var files = Session["Files"] == null ?
new List<HttpPostedFileBase>() :
(List<HttpPostedFileBase>)Session["Files"];
files.Add(NewsFilePath);
Session["Files"] = files;
}
return Content("");
}
but I have problem with this code.
when I upload one file, one file is stored into the session
when I upload two files, 4 files is stored into the session
when I upload three files, 6 files are stored into the session
What's the problem ?
Use .Distinct() while assigning files to the Session
public ActionResult GetFiles(HttpPostedFileBase NewsFilePath)
{
if (NewsFilePath != null)
{
var files = Session["Files"] == null ?
new List<HttpPostedFileBase>() :
(List<HttpPostedFileBase>)Session["Files"];
files.Add(NewsFilePath);
Session["Files"] = files.Distinct();
}
return Content("");
}
Hopefully, it will solve your problem, if not, post a comment below.
Consider the following code snippet
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(MyViewModel viewModel)
{
if (ModelState.IsValid)
{
//map properties here
using (var context = new MyEntities())
{
context.Users.Add(user);
context.SaveChanges();
}
if (Request.Files.Count > 0)
{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
if (file != null && file.ContentLength > 0)
{
//do checks and upload file here
}
}
}
}
return RedirectToAction("Index", "Home");
}
The form can be submitted as a standalone or with files which then get uploaded to a server. Now my issue is If I submit the form without any files or just one file then everything works as expected. However users can upload more than one file at a time and that's where the problem comes in. The files get uploaded but I get more than one entry in the database for that particular form. For example if the user uploads three files I'll get three entries in the database exactly that same.
So my question is how do I get around this?
On the client side I'm using DropZoneJs and calling the method as
<script>
Dropzone.autoDiscover = false;
var myDropZone = new Dropzone("#dzUpload", {
url: "/Home/Create",
autoProcessQueue: false,
previewsContainer: ".preview",
});
$("#submit-all").attr("type", "button").on('click', function (e) {
e.preventDefault();
e.stopPropagation();
if (myDropZone.getQueuedFiles().length > 0) {
myDropZone.options.autoProcessQueue = true;
myDropZone.processQueue();
}
else {
$("#dzUpload").submit();
}
});
</script>
I've also come across this question but I still have the same issue
It looks like the uploadMultiple option will change the behavior so only one request is sent to the server.
var myDropZone = new Dropzone("#dzUpload", {
url: "/Home/Create",
autoProcessQueue: false,
previewsContainer: ".preview",
uploadMultiple: true,
});
So if I am right the plugin will post the form for every file you drop into your plugin right?? One way is to generate a a GUID and maintain it in your form hidden input. So every time your plugin posts it will post this GUID as well. So change your insert statement into a upsert ( update or insert) based on the Guid.. You must save this GUID also along with your other data..
So every time you intend to insert check if the GUID already exist If so update it else insert new record.
I have tried to create a debug button as shown below taking reference from link#3 in bottom, I have compiled and configured the button in core database and configured the Commands.config but I am getting error message on the master database when I click from ribbon and sitecore admin client is restarted. I am not getting what the error message is points to.. !
Ribbon Button screen
Error Message Text
Control "system" does not exist on form. at Sitecore.Shell.Framework.Commands.CommandManager.GetMethodCommand(String command) at Sitecore.Shell.Framework.Commands.CommandManager.GetDispatchCommand(String command) at Sitecore.Web.UI.Sheer.ClientPage.Dispatch(String command) at Sitecore.Web.UI.Sheer.ClientPage.RaiseEvent() at Sitecore.Web.UI.Sheer.ClientPage.OnPreRender(EventArgs e)
Error Message screen
One more thing the link#2 mentioned in the bottom does not seems to contain the 'prototype zip available in the Resources section' as said by John in the blog post here.. can anyone see If I'm not wrong?
PS: link#1 is the old post to the link#2
Debug.cs code
using System;
namespace SitecoreDemo.Shell.Framework.Commands.System
{
[Serializable]
// implements the debug command on the Sitecore menu of the desktop
// and in the ribbon of the Content Editor
public class Debug : Sitecore.Shell.Framework.Commands.System.Debug
{
public override void Execute(Sitecore.Shell.Framework.Commands.CommandContext context)
{
// validate arguments and processing context
Sitecore.Diagnostics.Assert.ArgumentNotNull(context, "context");
Sitecore.Diagnostics.Assert.IsNotNull(Sitecore.Context.ClientPage, "ClientPage");
Sitecore.Diagnostics.Assert.IsNotNull(Sitecore.Context.ClientPage, "ClientResponse");
// ensure the new browser window authenticates as the current CMS user
// (in case the user formerly previewed as another user)
Sitecore.Publishing.PreviewManager.RestoreUser();
// open the new browser window
Sitecore.Web.UI.Sheer.SheerResponse.Eval("window.open('" + this.GetDebuggingUrl(context) + "', '_blank');");
}
// construct a URL to launch the debugger
private string GetDebuggingUrl(Sitecore.Shell.Framework.Commands.CommandContext context)
{
// whether to use the sc_lang query string parameter to specify the language
bool includeLanguage = Sitecore.Links.LinkManager.LanguageEmbedding != Sitecore.Links.LanguageEmbedding.Never;
// URL of the debugging window defaults to home page of managed site
Sitecore.Text.UrlString url = new Sitecore.Text.UrlString("/");
// enable all debugging options
url.Add("sc_debug", "1"); // enable the debugger
url.Add("sc_prof", "1"); // enable profiling
url.Add("sc_trace", "1"); // enable tracing
url.Add("sc_ri", "1"); // enable rendering information
// if the user has selected an item, ensure they have saved,
// then debug the item in the database and language associated with that item
if (context != null && context.Items != null && context.Items.Length > 0 && context.Items[0] != null)
{
Sitecore.Context.ClientPage.ClientResponse.CheckModified(false);
Sitecore.Data.Items.Item item = context.Items[0];
url.Add("sc_database", item.Database.Name);
url.Add("sc_itemid", item.ID.ToString());
if (includeLanguage)
{
url.Add("sc_lang", item.ID.ToString());
}
}
// if the user has not selected an item,
// if there is a content database, debug that database
// using the content language
else if (Sitecore.Context.ContentDatabase != null)
{
url.Add("sc_database", Sitecore.Context.ContentDatabase.Name);
if (includeLanguage)
{
url.Add("sc_lang", Sitecore.Context.ContentLanguage.Name);
}
}
// return a URL to open the debugger
return url.GetUrl();
}
public override Sitecore.Shell.Framework.Commands.CommandState QueryState(Sitecore.Shell.Framework.Commands.CommandContext context)
{
// if the user has selected at least one item
if (context.Items != null && context.Items.Length > 0 && context.Items[0] != null)
{
// if that item does not specify a layout for any device, disable this command
if (!this.HasLayoutForAnyDevice(context.Items[0]))
{
return Sitecore.Shell.Framework.Commands.CommandState.Disabled;
}
}
return base.QueryState(context);
}
// returns true if the item specifies a layout for any device
protected bool HasLayoutForAnyDevice(Sitecore.Data.Items.Item item)
{
Sitecore.Diagnostics.Assert.IsNotNull(item, "item");
// evaluate each device in the database containing the item
foreach (Sitecore.Data.Items.DeviceItem compare in item.Database.Resources.Devices.GetAll())
{
// if the item specifies layout details for that device, return true
if (item.Visualization.GetLayout(compare) != null)
{
return true;
}
}
// layout details for the item do not specify a layout for any device
return false;
}
}
}
Reference links:
Add a Button to the Sitecore Content Editor Ribbon to Debug Any Item in Any Database
Update: Add Debug Command to Content Editor in the Sitecore ASP.NET CMS
Professional Sitecore Development- Google Books
The prototype link has a zip file and contains the Debug.cs file.
Code below
using System;
namespace Sitecore.Sharedsource.Shell.Framework.Commands.System
{
[Serializable]
public class Debug : Sitecore.Shell.Framework.Commands.Command
{
public override void Execute(
Sitecore.Shell.Framework.Commands.CommandContext context)
{
Context.ClientPage.ClientResponse.CheckModified(false);
Sitecore.Data.Database contentDatabase = Context.ContentDatabase;
if ((context.Items != null) && (context.Items.Length == 1))
{
Sitecore.Data.Database database = context.Items[0].Database;
}
Sitecore.Text.UrlString webSiteUrl =
Sitecore.Sites.SiteContext.GetWebSiteUrl();
webSiteUrl.Add("sc_debug", "1");
if ((context.Items != null) && (context.Items.Length == 1))
{
Sitecore.Data.Items.Item item = context.Items[0];
if (item.Visualization.Layout != null)
{
webSiteUrl.Add("sc_itemid", item.ID.ToString());
}
webSiteUrl.Add("sc_lang", item.Language.ToString());
}
if (contentDatabase != null)
{
webSiteUrl.Add("sc_database", contentDatabase.Name);
}
webSiteUrl.Add("sc_prof", "1");
webSiteUrl.Add("sc_trace", "1");
webSiteUrl.Add("sc_ri", "1");
Context.ClientPage.ClientResponse.Eval(
"window.open('" + webSiteUrl + "', '_blank')");
}
}
}
Let me know if this code helps you and will get back to you if I find any more information.
The provided solution prototype at here on the blog post Update: Add Debug Command to Content Editor in the Sitecore ASP.NET CMS solved my issue, I have configured my own Debug.cs class file in the command and copied the Debug.item file from the solution prototype zip to folder location as specified in the post (and also mentioned below) and it is working now.
For references in future check below the steps as shown on the blog post to configure the solution prototype that helped me.
To create the command definition item using the serialization file:
Copy the Debug.item file from the prototype zip available in the
Resources section at the end of this blog post to the
/data/serialization/core/sitecore/content/Applications/Content
Editor/Ribbons/Chunks/Publish subdirectory of your Sitecore
solution, where the /data folder is typically a sibling of the
Website folder.
Log into the Sitecore desktop as an administrator.
Click the database icon in the lower right corner and then select
Core from the menu that appears (as described in the Sitecore Client
Configuration Cookbook).
Open the Content Editor, navigate to the
/sitecore/content/Applications/Content Editor/Ribbons/Chunks/Publish
item (copy that path to your clipboard, paste it into the search box
above the content tree, press Enter, select the first result).
On the Developer tab, in the Serialize group, click Revert Tree. If
you right-click the /sitecore/content/Applications/Content
Editor/Ribbons/Chunks/Publish item in the content tree and then
click Refresh from the submenu that appears, a new Debug item should
appear.
Remember to use the database icon to select the Master
database.
PS: However when I had created the debug item myself in content editor from core database it was not working don't know why.
My form looks like this
{
using (Ajax.BeginForm("Log",
new AjaxOptions {
UpdateTargetId = "lessonTable"
}))
//removed dropdown list ect... for readability
input type="submit" name = "submitButton" value = "Filter"
input type="submit" name = "submitButton" value = "Print Report"
and my controller does this
[HttpPost]
public ActionResult Log(lesson lesson,string submitButton)
{
/*Retreive all lessons*/
List<lesson> lessonList = (from l in storeDB.lessons
where l.statusID != DELETED
select l).ToList();
/*Filter retreived Lesson*/
lessonList = filterLesson(lesson,lessonList);
switch (submitButton)
{
case "Filter":
return PartialView(lessonList);
default:
{
return DetailsReport();
}
}
}
the DetailsReport() method returns a File
return File(renderedBytes, mimeType);
when click the Print Report button it is updating the div with the file header not requesting that the user opens the file. I have tried removing updatetarget ID but it doesn't prompt for a file download. Also when I make an ajax.actionlink call to the details report method it is working fine.
Thanks
If I understand what you are doing, it is working as intended; because you are making the request from an Ajax.BeginForm(), it is trying to display what ever is returned in the page. Removing the target would not be expected to change that.
You should simply make the "Print Report" button be part of a separate form or not a form at all, and have it pull the info it needs from the existing form before submitting (since it wouldn't do it automatically once it is removed from that form)
I have a problem with images in FCK editor. when i try to upload images it gives me Connector disabled error and the images are not showing in the editor page. i am programming with visual studio 2008. please help
Have a look at the following code:
private bool CheckAuthentication()
{
// WARNING : DO NOT simply return "true". By doing so, you are allowing
// "anyone" to upload and list the files in your server. You must implement
// some kind of session validation here. Even something very simple as...
//
// return ( Session[ "IsAuthorized" ] != null && (bool)Session[ "IsAuthorized" ] == true );
//
// ... where Session[ "IsAuthorized" ] is set to "true" as soon as the
// user logs in your system.
MembershipUser m = Membership.GetUser();
if (m != null)
{
return true;
} else {
return false;
}
//return false;
}
Then update both App and Root files.