Set file control value from model in asp.net mvc3 razor - asp.net-mvc

In my MVC application, I am using following code for a file.
MODEL
public HttpPostedFileBase File { get; set; }
VIEW
#Html.TextBoxFor(m => m.File, new { type = "file" })
Everything working fine .. for submitting value But I am trying to load file from controller model which is not working
CONTROLLER
public ActionResult ManagePhotos(ManagePhoto model)
{
if(ModelState.IsValid)
{
//upload file
}
else
{
return View(model); //contains type HttpPostedFileBase File { get; set; }
}
}
how can i load file input again if my validation fails as after returning, my file control is not mapped to model to file and it's empty...

If you know that the file is valid, and want to keep it temporarily, you can keep it in session (but be aware of memory usage).
If you know the file is valid, and want to keep it permanently, save it and just keep the path in memory.
If you know that the file is invalid, you wont want to nor often be able to keep it.
Often this is treated in the same way during validation failure as a password - it needs to be provided again and as such is requested for only when everything else is good.

if you want to go as far as it takes to made user experience seamless, then try following:
Add javascript on the client side to validation the user inputs
On the server side temporarily store all the files on the tmp file storage. Clean up files older than 10 minutes. Do this when you need to save files into the storage

Related

In MVC how can I edit records in memory without saving to database fisrt

I have a scenario in MVC where I am uploading Excel files using OPEN XML to read spreadsheets, I however do not want to save these records to the database yet, as I perform validation against the records and if validation succeeds I then save the record to the database, this is for performance reasons as I can have 1000's of records in the excel spreadsheet, I was able to edit well if I first save the records to the database, I would simply read them from db by Id , modify and then update/save the changes. I don't want to do this, I need to enable my app to read the the records in memory edit, re-validate then save only valid data, how can I do this in MVC, please see my current code below which uses the approach of saving the records first which is what I want to avoid.
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
CleanSupplierClaim cleanData = await db.CleanSupplierClaims.FindAsync(id);
if (cleanData == null)
{
return HttpNotFound();
}
return View(cleanData);
}
// POST: /Claim/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "Id,Action,Line_Number,Total_Claim,Currency,ClaimReference,ST_Key,Warning,Error_1,Error_2,Error,Domain_Username")] CleanSupplierClaim cleanData)
{
if (ModelState.IsValid)
{
if (cleanData.Id == 0)
{
db.CleanSupplierClaims.Add(cleanData);
}
else
{
db.Entry(cleanData).State = System.Data.Entity.EntityState.Modified;
}
await db.SaveChangesAsync();
//return PartialView();
}
return RedirectToAction("RedirectToValidateClaimsView");
}
Thank you in advance
HTTP is stateless. You have to write data somewhere.
"Somewhere" could be:
In page data (hidden form fields, JavaScript variables, etc.)
In cookies (not very suitable for large amounts of data)
In session state
In static variables (probably not good in a web application for a couple of reasons, but an option nonetheless)
In a file
In a separate database (maybe a local SQL database file for just that application, or maybe a document database, etc.)
In the main database but in separate tables (tables meant to hold "temporary" data which hasn't been committed to the "real" tables yet)
etc.
The point is, you have to write data somewhere. It doesn't have to be your main database tables. But if different requests to a web application need to operate on the same persistent data then that data needs to be persistent somewhere.
If you want to validate your Excel files:
Make a new class called Validation
Inside this class create a methode where you can validate your excel files.
Return true or false for valid or invalid.
For each excel file call this method and if it is valid, add it to a list with all your other valid excel files.
Save all valid excel files in your database
As far as I do not know your environment nor your validation criterias, it's hard for me to provide you any code. But maybe the list above can help you.

Saving multiple images with size limitation and bootstrap

I have built a simple ASP.NET MVC5 project that acts as a classifieds application for my college's students. I got everything figured out and implemented except for the images. I am struggling to find the best approach to store the images.
I came up with the following structure:
Ad represents the advertisement model
adImage represents an image(s) for an ad. AdImage has a foreign Key public int AdId { get; set; } and then public virtual Ad TheAdvertisement { get; set; }
Considerations:
I am using bootstrap
I will not consider support older IE browsers
I have to resize the images prior to save
I will be saving the images on the file system and then store their urls back into my database.
I think I know how to upload then store multiple images. I am struggling with how to implement size-limitation validation to my controller and whether it is something I should consider to implement in my project. What is the best approach when dealing with images in classified website?
To Limit the size of image files, take a look at file size upload limitation in ASP.NET MVC that employs web.config file to meet your purpose.
Another way to Limit file size is writing code something like this:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
//you can put your existing save code here
if (file != null && file.ContentLength > 10000)
{
//do whatever you want with the file
}
}
And the page File Upload ASP.NET MVC 3.0 contains good samples for you if you don't know how to write a controller to save files on file system.

MVC Get File Path from file selector

In MVC looking for a way to select a file from a browse/file selector, and then hit submit.
But when I hit submit I don't want to upload the actual file, just want to store/retrieve the filepath selected.
Looking at examples like this, it seems like the file gets uploaded and stored into memory which is not what I want.
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
You can use Path.GetFileName method to get the file name with extension. GetFileName method accepts the full path to the file, which you can obtain from the FileName property of the posted file.
If you do not want to save it to sever disk, Don't do that. Just read the file name and do what you want to do with that.
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file != null)
{
string justFileName=Path.GetFileName(file.FileName);
// No need to save the file. Just forget about it. You got your file name
//do somethign with this now
}
// TO DO : Return something
}
You need to import System.IO namespace to your class to use the Path class.
On the client capture the name of the file that the user selected and place it in a hidden file. When the user clicks submit, only submit the file name to an action method that takes string as input:
[HttpPost]
public ActionResult Index(string filename)
{
//Do something
}
Since you did not provide code on how you are selecting the file, I can only suggest that you use a plugin that allows you to hook in your own javascript for the selection event (I use KendoUI Upload).

User profile image asp.net mvc identity

I'm creating a web application using MVC 5 and Identity. I have so far created a registration system, but I would like to allow users to upload a profile when they register.
I was wondering if it is possible to implement profile pictures with asp.net identity?
Yes. Assuming you're using the default Entity Framework implementation, you can extend the ApplicationUser in a file called Models/IdentityModels.cs.
You can store the image in the database or elsewhere on the file system.
One way to store it in the database is using a byte array in the model (which I believe maps to varbinary(max))...
public class ApplicationUser : IdentityUser
{
public byte[] Image { get; set; }
}
Details on how to save upload an image and save in the database via EF can be found here...
Entity Framework 5 Code first adding an image
Or you can simply save the uploaded file to the file system or to blob storage, then store the path or URL to the image...
public class ApplicationUser : IdentityUser
{
public string ImagePath { get; set; }
}
Best thing todo is to create a second table (or add a column to the current table), add a file upload feature to the registration form. When registration is successful add the picture to the db with EntityFramework. Create a page to return the picture by the userid so you can include it in a page somewhere.
Something like this http://blogs.msdn.com/b/webdev/archive/2013/10/16/customizing-profile-information-in-asp-net-identity-in-vs-2013-templates.aspx but with a profile picture

Override partial class field in ASP MVC model

In my ASP MVC project, whenever I add a new table to my project two models are created. One under the Text Templating Transformation Toolkit (file w/.tt extension), and another outside this in the general Models folder (this one seems to want to default with a "1" at the end of the file).
Whenever a change is made to the database, it seems all the models under the .tt file are refreshed according to the fields currently existing in the database on that table. The files outside this is the general Models folder, however are left as they were. Because of this, we have put all of our model validation methods in these .cs files (with the "1" at the end of the file name).
However, in one instance I needed to remove a field from the model under the .tt file in order to perform a validation in the other .cs file. This is the validation I perform:
private string agentId;
//here, AgentId overrrides the field in the BankListAgentId.cs file,
//which MUST be commented out.
[DisplayName("Agent ID")]
public string AgentId
{
get { return agentId; }
set { agentId = this.scrubAgentId(value); }
}
Is there a way to specify in this .cs file that the AgentId field here (the file with the "1" at the end of the name) overrides the AgentId field in the.csfile found under the.tt` file?
As far as I know it can't be done. But there are few tricks that can you do.
Change name of your property to eg. InternalAgentId and also change in EDMX that field to be protected or even private. Then in your code reference to InternalAgentId:
public string AgentId
{
get { return this.InternalAgentId; }
set { this.InternalAgentId = this.ScrubAgentId(value); }
}
If you need that property in linq you can look at Microsoft Linq Translation
Another way is to change your T4 to generate partial methods and invoking it inside generated properties. I think that one of Entity Framework template already do that.

Resources