DNN MVC Module not posting file back - asp.net-mvc

I am building a small DNN MVC module whereby I need a user to upload file which will be processed server side.
When the form is posted back, the view model is posted back fine, but the file never is. Request.Files is always 0.
I even simplified it so all I had on the module was a simple file input and submit button but that failed as well.
I would hate to have to revert back to .ascx controls to get this to work.
I am testing this as an unregistered user, therefore there is no authentication checking in the controller.
See code below:
View
#inherits DotNetNuke.Web.Mvc.Framework.DnnWebViewPage<NM.Modules.FlexEventsCreate.Models.FlexEventViewModel>
#using DotNetNuke.Web.Mvc.Helpers
<input type="file" id="fileUp"/>
<input type="submit" id="btnSubmit" />
Controller
[DnnHandleError]
public class ItemController : DnnController
{
[HttpPost]
public ActionResult ShowForm(FlexEventViewModel flexEvent)
{
if (ModelState.IsValid)
{
var file = Request.Files;
if (file.Count != 0)
{
//do something
}
//return RedirectToDefaultRoute();
}
return View(flexEvent);
}
}
The rendered DNN HTML looks like this (I have simplified it)
<form method="post" action="/Test" id="Form" enctype="multipart/form-data">
<!-- Begin Content areas -->
<div>
<div class="row">
<div class="medium-9 columns">
<div id="dnn_LeftPane">
<div class="DnnModule DnnModule-DnnModule-747">
<a name="747"></a>
<div class="DnnF_Title_h1 SpacingBottom">
<h1><span id="dnn_ctr747_dnnTITLE_titleLabel" class="TitleH1"></span>
</h1>
<div id="dnn_ctr747_ContentPane">
<!-- Start_Module_747 -->
<div id="dnn_ctr747_ModuleContent">
<div id="dnn_ctr747_ShowForm_Prog" class="RadAjax RadAjax_Default" style="display:none;">
<div class="raDiv">
</div>
<div class="raColor raTransp">
</div>
</div>
<div class="RadAjaxPanel" id="dnn_ctr747_dnn_ctr747_ShowForm_UPPanel">
<div id="dnn_ctr747_ShowForm_UP">
<!-- 2013.2.717.40 -->
<div id="mvcContainer-747">
<input type="file" id="fileUp">
<input type="submit" id="btnSubmit">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>

I did do an upload in an MVC module using the dropzone jquery component - which may help you. See my sample Restaurant Menu project on github.
First, include the dropzone script and css:
#using DotNetNuke.Web.Client.ClientResourceManagement
#{
ClientResourceManager.RegisterStyleSheet(Dnn.DnnPage, "~/DesktopModules/MVC/DotNetNuclear/RestaurantMenu/Resources/dropzone/css/dropzone.css");
ClientResourceManager.RegisterScript(Dnn.DnnPage, "~/DesktopModules/MVC/DotNetNuclear/RestaurantMenu/Resources/dropzone/js/dropzone.min.js", 100);
}
Then place a container div for the upload component:
<div id="dZUpload" class="uploadform dropzone no-margin dz-clickable">
<div class="dz-default dz-message"></div>
</div>
Initialize the component and tell it what type and how many files can be uploaded:
$("#dZUpload").dropzone({
acceptedFiles: "image/jpeg,image/png,image/gif",
url: '#Url.Action("Upload", "Menu")',
maxFiles: 1, // Number of files at a time
maxFilesize: 1, //in MB
addRemoveLinks: true,
maxfilesexceeded: function (file) {
alert('You have uploaded more than 1 Image. Only the first file will be uploaded!');
},
success: function (response) {
}
});
Change the acceptedFiles to the mimetypes you are restricting ("application/pdf", etc). Change the maxFiles to limit how many files they can upload at a time.
Write an MVC controller action to respond to the Dropzone file upload url. You can see it expects an action method "Upload" on the controller "Menu" (MenuController.Upload):
public JsonResult Upload()
{
string imageUrl = string.Empty;
string imgPath = Server.MapPath("~/Portals/0/Restaurant/");
if (!Directory.Exists(imgPath))
{
Directory.CreateDirectory(imgPath);
}
foreach (string s in Request.Files)
{
var file = Request.Files[s];
if (file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(imgPath, fileName);
file.SaveAs(path);
imageUrl = string.Format("/Portals/0/Restaurant/{0}", fileName);
}
}
return Json(new { img = imageUrl, thumb = imageUrl });
}

Related

How to Fix message is not send Server to Client In SignalR Asp.net core 6

I do all thing but my message is not send from Server To client. I have two controller One is client and Another One is server controller they both have different View there have another Index view in server Controller And different Index view in Client .In server view I add Form And submit button and client view Used as result whenever I fill form and submit there result will be shown on client view page but it doesn't Work
This Is My Hub
public class NotificationHub:Hub
{
public async Task SendMessage(string message)
{
await Clients.All.SendAsync("ReceiveMsg", message);
}
}
This Is My client View Page
<h1>Client App</h1>
<div id="servermsg">
<ul id="msgList">
</ul>
</div>
<script src="~/lib/signalr/dist/browser/signalr.js"></script>
<script src="~/js/ClientNotification.js"></script>
This is My JavaScript File
"use strict";
var connection = new signalR.HubConnectionBuilder()
.withUrl("/notificationHub")
.build();
connection.start();
console.log(connection);
connection.on("ReceiveMsg", function (msg) {
console.log('message ',msg)
var li = document.createElement("li");
li.textContent = msg;
document.getElementById("msgList").appendChild(li);
})
var el = document.getElementById("#form-submit-btn");
if (el) {
el.addEventListener('click', () => {
connection.invoke("SendMessage", document.querySelector("#message-input").value);
});
}
This is my Server View Page
#model SignalR.Models.Notification
#{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<h4>Notification</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Index">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Message" class="control-label"></label>
<input asp-for="Message" id="message-input" class="form-control" />
<span asp-validation-for="Message" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" id="form-submit-btn" value="Send" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
<script src="~/lib/signalr/dist/browser/signalr.js"></script>
<script src="~/js/ClientNotification.js"></script>
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
This is my Model
public class Notification
{
public string? Message { get; set; }
}
Please What is the issue in My code that Server To client doesn't work
Change your js code:
var el = document.getElementById("#form-submit-btn");
to:
var el = document.getElementById("form-submit-btn");

kendo UI asynchronous uplaod on Razor Page returns 404

I am trying to use Kendo UI async upload on Razor Page (No controller) But I get 404 error
Index.cshtml page-
<div class="row">
<div class="">
<form asp-action="" class="" id="" enctype="multipart/form-data">
<div class="form-group">
<label class="">Review Type</label>
<div class="">
<select asp-for="ReviewType" asp-items="#(new SelectList(Model.ReviewTypes, "ReviewTypeLookupId", "ReviewTypeName"))" class="form-control"></select>
</div>
</div>
<div class="form-group">
<label class=""></label>
<div class="">
#(Html.Kendo().Upload()
.Name("files")
.Async(a => a
.Save("Index?handler=Save", "UploadManagement")
.Remove("Remove", "UploadManagement/Index")
.AutoUpload(true)
)
)
</div>
</div>
<div class="form-group">
<button type="submit" id="submit-all" class="btn btn-default">Upload </button>
</div>
</form>
</div>
Index.cshtml.cs Page
[HttpPost]
public ActionResult OnPostSave(IEnumerable<IFormFile> files)
{
// The Name of the Upload component is "files"
if (files != null)
{
foreach (var file in files)
{
//var fileContent = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
//// Some browsers send file names with full path.
//// We are only interested in the file name.
//var fileName = Path.GetFileName(fileContent.FileName.Trim('"'));
//var physicalPath = Path.Combine(HostingEnvironment.WebRootPath, "App_Data", fileName);
//// The files are not actually saved in this demo
////file.SaveAs(physicalPath);
}
}
// Return an empty string to signify success
return Content("");
}
Error -
Failed to load resource: the server responded with a status of 404 (Not Found)
The easiest way to solve this, is to not use .Save(string action, string controller) or any overload of this, but .SaveUrl(string url):
#(Html.Kendo().Upload()
.Name("files")
.Async(a => a
.SaveUrl("./Index?handler=Save")
.AutoUpload(true)
))
This will also work, if you are in a non-default area and the url to the page itself is acually /area-url/Index?handler=foo

How to check if a url belongs to a website that exists?

I am making a website where in a form, users can input a web page address. I was going to go with checking if the url is formatted correctly like an actual url which I think is the sloppy way and instead I want to check if url belongs to an actual website. Like, let's say user inputs www.pyrtyrmyrsyr.org, that is a valid address, but it doesn't lead to a website. Let's say user inputs www.python.org, that is both a valid address and leads to a website that exists.
And how can I check this validity before the form is sent and after input is given? Make the form's "send" button not clickable if url is not valid?
EDIT : Realized I didn't add any code of my view, apologize for that, also forgot to mention I use Bootstrap for View.
This is the form I use, what I am trying to do is use "Check" button, to check validity, by taking URL inside form-control with "id=url"
<div>
<div class="row">
<div class="col-md-12">
<h2 style="margin-left:20px; margin-top:10px">Add a Link</h2>
<form action="~/Link/Create" method="post">
<div class="form-group well clearfix" style="margin-left:20px; margin-right:20px; margin-top:20px">
<br />
<div class="row">
<label for="name" class="col-lg-2">URL:</label>
<div class="col-lg-9">
<input class="form-control" id="url" placeholder="URL" name="Address" /><br />
</div>
<div class="col-lg-1">
<button type="button" class="btn btn-primary" id="checkurl">Check</button>
</div>
</div>
<div class="row">
<div class="col-lg-2">
<label for="name">Interval:</label>
</div>
<!--<div class="col-lg-10">
<input class="form-control" placeholder="Interval to check (minutes)" name="Interval" /><br />
</div>-->
<div class="col-lg-5">
<select class="form-control" id="sel1">
<option>Minutes</option>
<option>Hours</option>
<option>Days</option>
<option>Weeks</option>
<option>Months</option>
</select>
</div>
<div class="col-lg-5">
<select class="form-control" id="sel2">
<option>Minutes</option>
<option>Hours</option>
<option>Days</option>
<option>Weeks</option>
<option>Months</option>
</select>
</div>
</div>
<div class="row">
<button class="btn btn-success pull-right" type="submit" style="width:200px; margin-right:15px">Save</button>
</div>
</div>
</form>
</div>
</div>
</div>
As far as I searched so far, connection to another domain/website is not possible using Javascript or anything similar so I need a server-side language, so I need to take this url, send it to control and return a true/false value after checking connection.
You can use Remote Validation in Asp.NET MVC. Let you have following property in your model.
public string URL {get; set;}
Add Remote attribute to your property like
[Remote("YourAction", "YourController", HttpMethod = "GET", ErrorMessage = "URL is not valid.")]
public string URL {get; set;}
Now write the following code in your specified action of the controller.
public class YourController : Controller
{
[AllowAnonymous]
public ActionResult YourAction(string URL)
{
try
{
//Check here by hitting your URL using HTTPClient or WebClient that it is returning something or not.
WebClient wc = new WebClient();
string HTMLSource = wc.DownloadString(URL);
return Json(true, JsonRequestBehavior.AllowGet); //Return true if it is valid.
}
catch (Exception)
{
return Json(false, JsonRequestBehavior.AllowGet); //Return false if it is not vald.
}
}
}
You must have to add following configurations in your web.config
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
Your code on view will be like
#Html.EditorFor(model => model.URL, new { type = "url", #class = "form-control", placeholder = "URL" } })
#Html.ValidationMessageFor(model => model.URL, "", new { #class = "text-danger" })
Solved it:
Added a bool to my model:
public bool Valid { get; set; }
Changed my view a little:
<div class="row">
<label for="name" class="col-lg-2">URL:</label>
<div class="col-lg-9">
<input class="form-control" id="url" placeholder="URL" name="Address" /><br />
</div>
<div class="col-lg-1">
<button type="button" class="btn btn-primary pull-right" id="checkurl">Check</button>
</div>
<input type="hidden" name="Valid" id="Validity"/>
</div>
Used the following codes, one for checking validity, other to reset form being usable if input is changed
$('#checkurl').click(function () {
var address = $('#url').val();
$.ajax({
url: "/Control/CheckUrl",
type: "POST",
data: JSON.stringify({ url: address }),
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
if (result) {
document.getElementById("Validity").value = true;
document.getElementById("saveBut").disabled = false;
}
else {
document.getElementById("Validity").value = false;
document.getElementById("saveBut").disabled = true;
}
},
async: true,
processData: false
});
});
$('#url').change(function ()
{
if (document.getElementById("saveBut").disabled == false)
{
document.getElementById("Validity").value = false;
document.getElementById("saveBut").disabled = true;
}
});
Ajax code there leads to a controller function that reformats URL a bit and checks validity:
public ActionResult CheckUrl(string url)
{
try
{
if (String.IsNullOrEmpty(url)) return Json(false, JsonRequestBehavior.AllowGet); ;
if (url.Equals("about:blank")) return Json(false, JsonRequestBehavior.AllowGet); ;
if (!url.StartsWith("http://") && !url.StartsWith("https://"))
{
url = "http://" + url;
}
WebClient wc = new WebClient();
string HTMLSource = wc.DownloadString(url);
return Json(true, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
It works flawlessly and as desired.

How can I export data in pdf using MVC?

This is My Index method by which I am getting the list of data in webgird.How can I write a method for exporting this list of data when I click on button?
public ActionResult Index(string eMailId)
{
var refEntry = _moneyReport.GetAll().Where(a => a.EmailId == eMailId).ToList();
var credittotal = _moneyReport.GetAll().Where(a => a.EmailId == eMailId && a.PromoValue < 0).Sum(a => a.PromoValue);
decimal TotalCredit = Convert.ToDecimal(credittotal * -1);
var debittotal = _moneyReport.GetAll().Where(a => a.EmailId == eMailId && a.PromoValue >0).Sum(a => a.PromoValue);
decimal TotalDebit = Convert.ToDecimal(debittotal);
ViewBag.TotDebit = TotalDebit;
ViewBag.TotCredit = TotalCredit;
if(TotalCredit>TotalDebit)
{
decimal FinalTotal = TotalCredit - TotalDebit;
ViewBag.Total = FinalTotal;
}
else
{
decimal FinalTotal = TotalDebit - TotalCredit;
ViewBag.Total = FinalTotal;
}
return View(refEntry);
}
This is my View page where I am entering an emailid,load and Export button`enter code here.
#using (Html.BeginForm())
{
<div class="container-fluid form-row">
<div class="col-md-12 no-padding">
<div class="col-md-3 no-padding">
<input type="text" name="eMailId" id="eMailId" />
<span class="highlight"></span>
<span class="bar"></span>
<label class="no-left">Enter Email Id <sup class="star">*</sup></label>
</div>
<div class="col-md-3">
<input type="text" id="gName" name="gName" readonly="readonly" />
<span class="highlight"></span>
<span class="bar"></span>
<label>Name</label>
</div>
<div class="col-md-3">
<input type="submit" id="btnLoad" class="btn btn-md pm-create" value="Load" />
<input type="submit" id="btnLoad" class="btn btn-md" value="Export To PDF" />
</div>
<input type="hidden" id="HdnEmail" value='#TempData["MailID"]' />
</div>
</div>
}
<div id="report-grid">
#{Html.RenderPartial("ImportMoneyReport", Model);}
</div>
ImPortMoneyReport is my partial page where i ve the webgrid.
To export model data to PDF you will have to use one of third party pdf export libraries such as few below. You will find sample examples on respective sites or google them. You will need to implement code to export pdf in and add that file/stream into Response.OutputStream by setting respective content type in ImportMoneyReport action. Also you will have to invoke ImportMoneyReport method on post/event you can not use Html.RenderPartial to export; otherwise you can put export code in Index action only.
PDF Sharp
iTextSharp
It you want something that's working and very easy to use. Take a look at https://github.com/andyhutch77/MvcRazorToPdf
Just read the documentation.
For sample code. Take a look at this.
https://github.com/andyhutch77/MvcRazorToPdf/tree/master/MvcRazorToPdfExample
If you encounter some issues go to their github page and click the Issues tab, maybe some of your questions are already resolved there.
P.S.
Some of the PDF libraries like Rotativa will require an executable program to run that will not work when your app is deployed to Azure because Azure doesn't support exe files (I guess for security purposes) else you'll create a webjob just for the exe file.

Refreshing captcha reloads the whole page

I'm new to JSON and jqueries.
I created a captcha as below in cshtml file
<div class="row-fluid">
<div class="span3"></div>
<iframe id="CaptchaIfram" src="#Url.Action("ShowCaptchaImage")" scrolling="no"></iframe>
<div>
<div class="span3"></div>
<input id="RefreshCaptcha" type="submit" onclick="captcha()" value="Refresh" class="btn btn-success" />
</div>
</div>
<script type="text/javascript">
function captcha()
{
document.getElementById("CaptchaIfram").contentDocument.location.reload(true);
}
</script>
in Controller:
public Captcha ShowCaptchaImage(int width, int height, int totalcharacters)
{
return new Captcha(width, height, totalcharacters);
}
Its working fine and if I click on refresh button, whole page getting refreshed as I'm using Url.Action method.
To avoid this, I used JSON as below. But image is not getting displayed.
Can anybody let me know where I need to correct.
<div class="row-fluid">
<div class="span3"></div>
<iframe id="CaptchaIfram" onload="showCaptcha()" scrolling="no"></iframe>
<div>
<div class="span3"></div>
<input id="RefreshCaptcha" type="submit" value="Refresh" onclick="showCaptcha()" class="btn btn-success" />
</div>
</div>
<script type="text/javascript">
function showCaptcha()
{
var url = "/ESignature/ShowCaptchaImage";
var target = '#CaptchaIfram';
$.getJSON(url, { width: 200, height: 35, totalcharacters: 5 }, function (data) {
document.getElementById("CaptchaIfram").src = data;
});
}
</script>
public JsonResult ShowCaptchaImage(int width, int height, int totalcharacters)
{
return Json(new Captcha(width, height, totalcharacters), JsonRequestBehavior.AllowGet);
}
I changed the type of refresh button to client side button as below. It didn't refresh the whole page.
No Json functions are required. (second code block in my question)

Resources