uploading PDF files and preview the uploaded files in ASP.net MVC3 - asp.net-mvc-3

i am a newbie in ASP.net MVC3 application.
I am working on this project where i have to work with PDF files.
I must be able to upload the PDF files to my file server and as soon as the file is uploaded the user must be able to see the preview of the uploaded document on the same page.
the Preview must be loaded in some DIV or partial view.
I have been spending a lot of time in research but still could not get what i need.
If anyone can help m with this i'll be very grateful.

public class FileUploadController[HttpPost]{
public ActionResult UploadFile(HttpPostedFileBase uploadFile){
//Save file to server
return new FileContentResult(fileContents, contentType);
}
}
#using (Html.BeginForm("UploadFile", "FileUpload", FormMethod.Post, new { enctype = "multipart/form-data" })){
<input type="file" name="uploadFile" id="uploadFile" />
<input type="submit" name="FileUpload" value="Upload" id="FileUpload"/>
}

Related

How to pass ViewModels into Razor Components in .NET Core 3.1

I have a View MyView.cshtml with the following content:
#using MyProject.ViewModels
#model MyProject.ViewModels.MyViewViewModel
<form asp-action="Test" method="Post">
<component type="typeof(MyProject.Views.Home.Test)" render-mode="ServerPrerendered" />
<input type="submit" value="send"/>
</form>
And I have the Razor Component Test.razor with the following content (with Blazor Syntax):
#page "/Test"
<div class="form-group top-buffer #Visible">
<div class="row">
<div class="col-2">
<label asp-for="TestName" class="control-label"></label>
</div>
<div class="col-3">
<input asp-for="TestName" class="form-control" />
<span asp-validation-for="TestName" class="text-danger"></span>
</div>
</div>
</div>
<button #onclick="Show">Show</button>
#code {
public string Visible { get; set; } = "hidden";
protected async Task Show()
{
Visible = "";
}
}
The Class MyViewViewModel would look like this:
namespace MyProject.ViewModels
{
public class MyViewViewModel
{
[Display(Name = "Test Name:")]
public string TestName { get; set; }
}
}
Works all pretty fine so far. However I now want to use this component as part of a Web form which will be sent to the controller after submission. That's why I need to access and change properties of my ViewModel 'MyViewViewModel'. Unfortunately I did not find any answer in the internet on how to do that. I can't use #model MyProject.ViewModels.MyViewViewModel like in the view because this will give me a compilation error. I wonder if I need to use #inject, but if yes, I don't know how...
(parts are used from this example: https://jonhilton.net/use-blazor-in-existing-app/)
When you mix Blazor in a Razor Page, you can do the following:
Render a Razor Component
Interact with a Razor Component
Pass a Razor Component values
Please keep in mind that you are dealing with two different life-cycles. So if you do work inside of a Razor Component, the component will update but not effect the Razor Page it is hosted inside of. So mixing Razor Components and Pages with forms would be difficult.
More specifically to the OP. To pass data from your ViewModel to the component you may use the following method.
#using MyProject.ViewModels
#model MyProject.ViewModels.MyViewViewModel
<form asp-action="Test" method="Post">
<component type="typeof(MyProject.Views.Home.Test)"
render-mode="ServerPrerendered"
param-Name="#Model.TestName"/>
<input type="submit" value="send"/>
</form>
Test.razor
<h3>HelloWorld</h3>
Hello #Name
#code {
[Parameter]
public string Name { get; set; } = "undefined";
}
About life cycles
Basically when you have a button in Blazor, it will trigger an event which causes the component to re-render. You could imagine it like an iframe, or update-panel. When you have a button in a Razor page, it does a HTTP call round trip and reloads the page entirely. There is no event system in place to tell Blazor to invoke an HTTP call round trip to refresh the Razor page's content and vise versa. You can only one-way data-bind from Razor pages to Blazor, think write-only, and only when the page loads.
To hopefully add to the info. With a ASP.Net Core MVC project host Blazor webassembly, I was trying to pass a viewmodel into a razor component using this code in my view cshtml file:
<component Type="typeof(Leave)" render-mode="WebAssembly" model="new { model = (MyViewModel)#Model})"/>
But it would fail to render the razor component if I tried to access data in the viewmodel from the razor component with an Object not set exception. I think it was accessing the data before the view model has been initialized. Maybe if I set a default value this could avoided?
I found by using this instead I was able to get it working.
#(await Html.RenderComponentAsync<Leave>(RenderMode.WebAssembly,new { model = (MyViewModel)#Model}))
Edit
Seems you also need to register the viewModel class in the services in the Blazor WASM project in the Program.cs file.
builder.Services.AddScoped(sp => new HttpClient {BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddScoped<MyViewModel,MyViewModel>(); // <= add this line
await builder.Build().RunAsync();`
Without that I would get an error saying the property could not be found.
Hopefully this saves someone else some time :-)

.NET change searched locations web views in MVC4

I'm a newbie in web language.
I started a .NET project on my visual studio 2010, it's in MVC 4 and razor structure.
The problem is that i had an folder in the views folder, with a view in it, but when i try to access the view i got this error:
The view 'searchWeb' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Home/searchWeb.aspx
~/Views/Home/searchWeb.ascx
~/Views/Shared/searchWeb.aspx
~/Views/Shared/searchWeb.ascx
~/Views/Home/searchWeb.cshtml
~/Views/Home/searchWeb.vbhtml
~/Views/Shared/searchWeb.cshtml
~/Views/Shared/searchWeb.vbhtml
I guess he is not searching in the right folder...but how to change this ?
I looked some topics and apparently i have to make a new viewEngine and inherirted from the old one ?
Is it possible to fix it without making a new view engine ? or can you show me how to make the new view engine ? thank you !
EDIT:
this is my homeController.cs:
namespace Searcher.Controllers
{
public class HomeController : Controller
{
public ActionResult homeWeb()
{
ViewBag.Message = "Searching for sites over the web.";
return View();
}
public ActionResult homeImages()
{
ViewBag.Message = "Searching for images over the web.";
return View();
}
public ActionResult homeVideos()
{
ViewBag.Message = "Searching for videos over the web.";
return View();
}
[HttpPost]
public ActionResult searchWeb()
{
// do something with the search value
return View();
}
}
}
and this is my homeWeb, which is calling the searchWeb:
#{
ViewBag.Title = "Search Web";
}
#section featured {
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>#ViewBag.Title.</h1>
<h2>#ViewBag.Message</h2>
</hgroup>
</div>
</section>
}
#using (Html.BeginForm("searchWeb", "Home", FormMethod.Post, new { id = "searchForm" }))
{
<div class="main-block">
<p>
<div>
<input size="200px" type="text" name="searchValue" />
</div>
<div>
<input type="submit" value="Submit" />
</div>
</p>
</div>
}
So where is your searchWeb.cshtml file?
Your controller is telling the view engine to look for the search.Web.cshtml file in the Home controller, which normally translates to
~/View/Home/searchWeb.cshtml (one of the default search locations you mentioned in your question).
Its not recomended to change view search location. Trust me:). Especially for newbie in MVC.
And you dont need to change it, this must working from the box.
So make shure that the view location is right. As i can see for this view you need create the action
in Home Controller like
public ActionResult searchWeb()
{
return View();
}
or you trying to call thi view as partial?

load data into file upload MVC3

Html code:
#using (Html.BeginForm("Edit", "RoomInfo", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" class="multi" />
<p>
<input type="submit" value="Update" />
</p>
}
Controller code;
public ActionResult Search(string id)
{
var arrayid = id.Split(',');
int roomid = int.Parse(arrayid[0]);
ViewBag.ImageID = new SelectList(db.RoomImgs.Where(p => p.RoomID == roomid), "ImageID", "FilePath");
return View(roominformation);
}
I'm trying to upload the image into server and insert the file path into database and I successful to insert in to server and database, but now I need to select out the file path and put into the file upload tag in Edit mode. I trying some method but still fail to set in. How can I do it?
If what you're trying to do is display the previously uploaded image and then allow users to modify the image.
You can't populate the file input like you would a text box. What most websites do is display the image above the input and then have the input box below if you want to change the image. If you want to remove the image then you could also have a checkbox for removing the image. Then on the server side you have to check if the checkbox is checked and clear the image or, if the file input is populated store the new image and update the database.

Trouble uploading file ASP.NET MVC3. XML file to Model

I'm attempting to upload an xml file to my site. However, regardless of which file I attempt to upload, the HttpPostedFileBase element in my code is null. I don't understand why this is. I've followed all the examples I can find on uploading files and it doesn't seem to make any sense. This is the controller method
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase xmlFile)
{
if (xmlFile != null && xmlFile.ContentLength > 0)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFile.InputStream);
// other logic later
return RedirectToAction("Index");
}
return RedirectToAction("UploadFailed");
}
and the cshtml:
#{
ViewBag.Title = "Upload";
}
#using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="OK" />
}
It has a wrong name. The action argument is called xmlFile whereas your file input is called file. You need to be consistent in your naming conventions:
<input type="file" name="xmlFile" />
I also invite you to checkout Phil Haack's blog post on this subject.

File Uploading MVC3 and Microsoft Web Helpers

I am currently using the file upload helper that comes with Microsoft.WebHelpers like this
#FileUpload.GetHtml(initialNumberOfFiles: 1, allowMoreFilesToBeAdded: true, includeFormTag: false, uploadText: "Upload")
This correctly gives me a upload box but I am having two problems with this that I cannot seem to find an answer for.
The first problem is the box does not display the filename correctly if I have a long path.
The second problem is that I can add a bunch of new files but there does not seem to be a remove option that can be turned on.
I need to find a good tool to facilitate file uploads that will give me these options and seamlessly integrate with asp.net mvc3 or figure out a way to do this with the upload tool.
I am not sure what current tools are as far as nuGet packages go. However, I know that you can roll your own pretty easily.
In view:
#using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
...
<input type="file" id="files" name="files" size="60" /><input type="button">
...
<input type="submit">
}
<script>function(){ //make button add another input field with id="files"}
</script>
Note: new { enctype = "multipart/form-data" } is required to send files to the controller from a form.
In Action:
[HttpPost]
public ActionResult ActionName(IEnumerable<HttpPostedFileBase> files)
{
foreach(HttpPostedFileBase uploadFile in files)
{
//work with uploadFile
}
}

Resources