In previous versions of ASP.NET, an uploaded file was represented by an instance of
System.Web.HttpPostedFileBase
. This has been replaced in ASP.NET 5 (Core 1.0) by IFormFile
, which is found in theMicrosoft.AspNet.Http
namespace or Microsoft.Extensions.PlatformAbstractions package. It shares a few of the same properties and methods as its predecessor, but it also has its differences, as shown by example.- Firstly we create a ViewModel for our Form:This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
namespace OpenBizz.ViewModels { public class ProductViewModel { [Required] [StringLength(27,MinimumLength =7)] public string ProductName { get; set; } [Range(0,9999999999999999)] public decimal ProductPrice { get; set; } [Required] [StringLength(500, MinimumLength = 19)] public string ProductDescription { get; set; } [Range(0,20000)] public int QuantityOnHand { get; set; } [Required] [DataType(DataType.Date)] public DateTime DateOut { get; set; } [Required] [Display(Name = "Select Warehouse")] public int WarehouseID { get; set; } [Required] public List<Warehouse> Warehouses { get; set; } [Required] public List<ProductCategory> Categories { get; set; } [Required] [Display(Name = "Select Category")] public int CategoryID { get; set; } [Required(ErrorMessage ="Please Upload a Valid Image File")] [DataType(DataType.Upload)] [Display(Name ="Upload Product Image")] [FileExtensions(Extensions ="jpg,png,gif,jpeg,bmp,svg")] public IFormFile ProductImage { get; set; } } }
- Then Create our actual Form in Create.cstmlThis file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
@model OpenBizz.ViewModels.ProductViewModel <h2>Create</h2> <form asp-controller="Products" asp-antiforgery="true" asp-action="Create" enctype="multipart/form-data" method="post"> <div class="form-horizontal"> <h4>Product</h4> <hr /> <div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="ProductName" class="control-label col-md-2"></label> <div class="col-md-10"> <input asp-for="ProductName" class="form-control" /> <span asp-validation-for="ProductName" class="text-danger"></span> </div> </div> <div class="form-group"> <label asp-for="ProductDescription" class="control-label col-md-2"></label> <div class="col-md-10"> <textarea asp-for="ProductDescription" class="form-control"></textarea> <span asp-validation-for="ProductDescription" class="text-danger"></span> </div> </div> <div class="form-group"> <label asp-for="CategoryID" class="control-label col-md-2"></label> <div class="col-md-10"> <select asp-for="CategoryID" asp-items="@(new SelectList(Model.Categories, "CategoryID", "CategoryName"))" class="form-control"></select> <span asp-validation-for="CategoryID" class="text-danger"></span> </div> </div> <div class="form-group"> <label asp-for="ProductPrice" class="control-label col-md-2"></label> <div class="col-md-10"> <input asp-for="ProductPrice" class="form-control" /> <span asp-validation-for="ProductPrice" class="text-danger"></span> </div> </div> <div class="form-group"> <label asp-for="QuantityOnHand" class="control-label col-md-2"></label> <div class="col-md-10"> <input asp-for="QuantityOnHand" class="form-control" /> <span asp-validation-for="QuantityOnHand" class="text-danger"></span> </div> </div> <div class="form-group"> <label asp-for="WarehouseID" class="control-label col-md-2"></label> <div class="col-md-10"> <select asp-for="WarehouseID" asp-items="@(new SelectList(Model.Warehouses, "WarehouseID", "WarehouseName"))" class="form-control"></select> <span asp-validation-for="WarehouseID" class="text-danger"></span> </div> </div> <div class="form-group"> <label asp-for="DateOut" class="control-label col-md-2"></label> <div class="col-md-10"> <input asp-for="DateOut" class="form-control datepicker-inline" /> <span asp-validation-for="DateOut" class="text-danger"></span> </div> </div> <div class="form-group"> <label asp-for="ProductImage" class="control-label col-md-2"></label> <div class="col-md-3"> <input asp-for="ProductImage" class="form-control" /> <span asp-validation-for="ProductImage" class="text-danger"></span> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div> </div> </form>
- Now we move to our Products Controller:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
namespace OpenBizz.Controllers.Web { public class ProductsController : Controller { private ILogger<ProductsController> _logger; private IRepository<Product> _products; private IRepository<Warehouse> _warehouses; private IRepository<ProductCategory> _categories; private IApplicationEnvironment _appEnvironment; public ProductsController(IApplicationEnvironment appEnvironment, IRepository<Product> products, IRepository<Warehouse> warehouses, IRepository<ProductCategory> categories, ILogger<ProductsController> logger) { _products = products; _warehouses = warehouses; _categories = categories; _appEnvironment = appEnvironment; _logger = logger; } public IActionResult Index() { try { return View(_products.GetAll().ToList()); } catch (Exception ex) { _logger.LogDebug(ex.Message); throw; } } public IActionResult Create() { try { ProductViewModel p = new ProductViewModel() { Categories = _categories.GetAll().ToList(), Warehouses = _warehouses.GetAll().ToList() }; return View(p); } catch (Exception ex) { _logger.LogDebug(ex.Message); throw; } } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Create(ProductViewModel product, IFormFile ProductImage) { try { if (ModelState.IsValid) { if (ProductImage != null && ProductImage.Length > 0) { var parsedContentDisposition = ContentDispositionHeaderValue.Parse(ProductImage.ContentDisposition); string FilePath = parsedContentDisposition.FileName.Trim('"'); string FileExtension = Path.GetExtension(FilePath); var uploadDir = _appEnvironment.ApplicationBasePath + $@"\Uploads\Images\{product.ProductName}\"; if(!Directory.Exists(uploadDir)) { Directory.CreateDirectory(uploadDir); } var imageUrl = uploadDir + product.ProductName + FileExtension; ProductImage.SaveAs(imageUrl); } var newProduct = Mapper.Map<Product>(product); _products.Add(newProduct); if (_products.SaveAll()) { RedirectToAction("Index"); } } ProductViewModel p = new ProductViewModel() { Categories = _categories.GetAll().ToList(), Warehouses = _warehouses.GetAll().ToList() }; return View(p); } catch (Exception ex) { _logger.LogDebug(ex.Message); throw; } } } }
I think it is very early to make dotnetcore publicly available as you cant carry out most of the basic tasks a dev typically would want to do. Also I am curious how often a dev changes an ORM to require a repository pattern? Especially if the reason is to show a sample code like this.
ReplyDeleteRegarding .NET Core, yes it's not yet ready for production, no matter what Microsoft says. And as for the Repository Pattern, a typical scenario for changing ORM would be if you want to jump onto NoSQL bandwagon. Btw, you can easily substitute Repository Function calls with Entity Framework Function Calls. Hope this helps. Cheers.
DeleteHi, I've followed your tutorial and faced some issues.
ReplyDeleteI wrote the issue on StackOverflow
http://stackoverflow.com/questions/40447338/adding-images-to-asp-net-core
replied.
DeleteHey it seems you need to learn basics of web development using MVC frameworks in general. I can teach you via skype if you need help. But please avoid posting these kind of general / noob(ish) questions on stackoverflow. And first learn the basics and then jump onto advance topics like these. Hope this helps.
DeleteThis comment has been removed by the author.
ReplyDeleteFileextesnions attribute only works with string type.
ReplyDeleteI am really happy with your blog because your article is very unique and powerful for new reader.
ReplyDeleteselenium training in chennai
This blog is the general information for the feature. You got a good work for these blog.We have a developing our creative content of this mind.Thank you for this blog. This for very interesting and useful.
ReplyDeleterpa Training in Chennai
rpa Training in bangalore
rpa Training in pune
blueprism Training in Chennai
blueprism Training in bangalore
blueprism Training in pune
iot-training-in-chennai
Thanks for your informative article, Your post helped me to understand the future and career prospects & Keep on updating your blog with such awesome article.
ReplyDeleteData Science training in marathahalli
Data Science training in btm
Data Science training in rajaji nagar
Data Science training in chennai
Data Science training in electronic city
Data Science training in USA
Data science training in pune
Data science training in kalyan nagar
Thank you for an additional great post. Exactly where else could anybody get that kind of facts in this kind of a ideal way of writing? I have a presentation next week, and I’m around the appear for this kind of data.
ReplyDeletepython training in velachery
python training institute in chennai
Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
ReplyDeleteDevops training in velachery
Devops training in annanagar
Devops training in tambaram
DevOps online Training
Your story is truly inspirational and I have learned a lot from your blog. Much appreciated.
ReplyDeleteBlueprism training in velachery
Blueprism training in marathahalli
Really great post, I simply unearthed your site and needed to say that I have truly appreciated perusing your blog entries.
ReplyDeleteangularjs Training in bangalore
angularjs Training in btm
angularjs Training in electronic-city
angularjs online Training
angularjs Training in marathahalli
I am definitely enjoying your website. You definitely have some great insight and great stories.
ReplyDeletedevops online training
aws online training
data science with python online training
data science online training
rpa online training
ReplyDeleteThanks for sharing the knowledgeable stuff to enlighten us no words for this amazing blog.. learnt so many things I recommend everyone to learn something from this blogger and blog.. I am sharing it with others also
IT Software Training in Chennai | Python Training in Chennai | Dot Net Training in Chennai |Android Training in Chennai
Title:
ReplyDeleteBest Oracle Training in Chennai | Infycle Technologies
Description:
If Oracle is a job that you're dreaming of, then we, Infycle are with you to make your dream into reality. Infycle Technologies offers the best Oracle Training in Chennai, with various levels of Oracle courses such as Oracle PLSQL, Oracle DBA, etc., in 100% hands-on practical training with professional tutors in the field. Along with that, the mock interviews will be done for the candidates, so that, they can face the interviews with full confidence.
Best traiing in Chennai
Description:
ReplyDeleteInfycle Technologies is the best software training center in Chennai, providing amazing Data Science training in Chennai which will be realistic and taught by industry experts. Aside from practical training preparation, mock interviews will be arranged for students so that they can confidently face the interviews. All of this will be packed up by full placement assurance with the best salary package from top companies. For having a free demo session, call 7502633633.
best training institute in chennai
Smart move for your career is Choosing to do Oracle Course in Chennai at Infycle!! Do you know why this name is chosen for Infycle. Infycle where the place we offered Infinity of Oracle.
ReplyDeleteYes!!! But not only Oracle, More than 20+ courses are offered here 5000+ students are placed in top MNC’s Company with good salary packages. For admission 7502633633 Oracle Course in Chennai | Infycle Technologies
Pull- up your socks and knot your tie. Gonna have a good salary package job after completing Big-data H adoop training in Chennai at Infycle. Infylce is completely for Software training and placement by friendly trainees, good atmosphere, 200% practical classes, and more.
ReplyDeleteHarrah's Cherokee Casino & Hotel - MapYRO
ReplyDeleteWelcome to Harrah's 서산 출장샵 Cherokee Casino 구리 출장마사지 & Hotel, where fun is always fun. The location is convenient to Murphy at 포항 출장안마 Cherokee Casino 천안 출장샵 Parkway and 사천 출장샵 Murphy at
mmorpg oyunlar
ReplyDeleteINSTAGRAM TAKİPCİ SATIN AL
tiktok jeton hilesi
Tiktok jeton hilesi
Antalya saç ekim
referans kimliği nedir
instagram takipçi satın al
Metin pvp
İnstagram Takipci Satın Al
Yeni Perde Modelleri
ReplyDeletesms onay
Turkcell mobil ödeme bozdurma
nft nasıl alinir
Ankara evden eve nakliyat
trafik sigortası
dedektör
web sitesi kurma
AŞK KİTAPLARI