How to Upload 2 Image Files into MVC C# 5 database in its respective Byte[] array property? - database

public class Opportunity
{
[Key]
public int OpportunityId { get; set; }
[Required(ErrorMessage = "Graphics Image is required")]
public byte[] Graphics { get; set; }
[DisplayName("Faculty Picture")]
[Required(ErrorMessage = "Faculty Image is required")]
public byte[] FacultyPicture { get; set; }
}
Controller:
namespace Kaust.Views.Opportunities
{
public class OpportunitiesController : Controller
{
private KaustContext db = new KaustContext();
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "OpportunityId,Graphics,FacultyPicturen")] Opportunity opportunity)
{
if (ModelState.IsValid)
{
db.Opportunities.Add(opportunity);
db.SaveChanges();
return RedirectToAction("Index");
}
}
View:
Create index:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Opportunity</h4>
<hr />
#Html.Images(m => m.Graphics, "Graphics", "id")
#Html.ValidationMessageFor(model => model.Graphics, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-horizontal">
<h4>Opportunity</h4>
<hr />
#Html.Images(m => m.FacultyPicture, "Graphics", "id")
#Html.ValidationMessageFor(model => model.FacultyPicture, "", new { #class = "text-danger" })
</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>
}
And #Html.Images is a customhelper:
public static IHtmlString Images<TModel,TValue>(this HtmlHelper<TModel> helper,System.Linq.Expressions.Expression<Func<TModel, TValue>> expression, string name, string id){
TagBuilder tb = new TagBuilder("input");
tb.Attributes.Add("ex", expression.ToString());
tb.Attributes.Add("name", name);
tb.Attributes.Add("id", id);
tb.Attributes.Add("type", "file");
tb.Attributes.Add("accept", "Image/*");
return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));
}
}
It creates this output:
<input accept="Image/*" ex="m => m.Graphics" id="id" name="Graphics" type="file">
When I click the submit button:
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
I have seend several methods to change the image file to Byte[] but I just don't know how to do it before the submit button or because it doesn't get into the "httppost method".
I have tried this solutions. but... I still get the error.
How to upload/display images using ASP.net MVC4 with Entity Framework
http://www.prideparrot.com/blog/archive/2012/8/uploading_and_returning_files
The question is how can I save this files into the databases in after clicking the submit button?

The properties in your model need to be HttpPostedFileBase (not byte[]) for binding to a file input in the view. Since your also wanting to store the filein the data base, you will need a separate view model and data model
// View model (Note ID property not required)
public class OpportunityVM
{
[Required(ErrorMessage = "Image is required")]
public HttpPostedFileBase Graphics { get; set; }
[DisplayName("Faculty Picture")]
public HttpPostedFileBase FacultyPicture { get; set; }
}
And in the POST method
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([OpportunityVM model)
{
if(!ModelState.IsValid)
{
return View(model);
}
// Initialize data model
Opportunity opportunity = new Opportunity();
using (var reader = new System.IO.BinaryReader(model.Graphics.InputStream))
{
opportunity.Graphics = reader.ReadBytes(model.Graphics.ContentLength);
}
if (model.FacultyPicture != null && modelFacultyPicture.ContentLength > 0)
{
// ditto for FacultyPicture
}
db.Opportunities.Add(opportunity);
db.SaveChanges();
return RedirectToAction("Index");
}
Note that you also need to include the enctype = "multipart/form-data" attribute in the form tag
#using (Html.BeginForm("Create", "Opportunities", FormMethod.Post, new { enctype = "multipart/form-data" }))
Side note: Your generating invalid html. Both file inputs in your model have id="id" (duplicate id attributes)
There is no need to pass the name and id to the helper (and in fact a minor typo passing the name means binding will fail). Instead use the ModelMetadata to generate the correct attributes. In addition, ex is not a valid attribute and its not clear what you are trying to achieve with tb.Attributes.Add("ex", expression.ToString()); but it should be removed.
public static IHtmlString Images<TModel,TValue>(this HtmlHelper<TModel> helper,System.Linq.Expressions.Expression<Func<TModel, TValue>> expression)
{
string name = ExpressionHelper.GetExpressionText(expression);
string id = HtmlHelper.GenerateIdFromName(name);
TagBuilder tb = new TagBuilder("input");
// tb.Attributes.Add("ex", expression.ToString());
tb.MergeAttribute("name", name);
tb.MergeAttribute("id", id);
tb.MergeAttribute("type", "file");
tb.MergeAttribute("accept", "Image/*");
return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));
}

Related

Save ASP.NET core Identity User attributes in another table

I am developing an ASP .NET core web application. I employ Identity UI framework for the user registration and authorization in the application. I inherit Identity User to my ApplicationUser class as follows. It creates a table called as ApplicationUser and save the relevant data under the given attributes successfully: (I am using Microsoft SQL database)
ApplicationUser.cs
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
#nullable disable
namespace WebApp.Models
{
public partial class ApplicationUser : IdentityUser<int>
{
public ApplicationUser()
{
}
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastNam { get; set; }
public DateTime? DateOfBirth { get; set; }
public string Bio { get; set; }
public virtual UserAddress UserAddress { get; set; }
}
}
Then I implemented UserAddress model class as follows. It creates another table in the database named as "UserAddress"\
UserAddress.cs
using System;
using System.Collections.Generic;
#nullable disable
namespace WebApp.Models
{
public partial class UserAddress
{
public int UserId { get; set; }
public string BuildingNo { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public virtual ApplicationUser User { get; set; }
}
}
Next in under Areas folder in Identity UI frame work, I change the Index.cshtml file as follows. i inserting new entry to enter the building number of the user, that should be saved in UserAddress table in database.
Index.cshtml
#page
#model IndexModel
#{
ViewData["Title"] = "Profile";
ViewData["ActivePage"] = ManageNavPages.Index;
}
<h4>#ViewData["Title"]</h4>
<partial name="_StatusMessage" model="Model.StatusMessage" />
<div class="row">
<div class="col-md-12">
<form id="profile-form" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="=row d-flex flex-row">
<div class="form-group col-md-6">
<label asp-for="Input.UserName"></label>
<input asp-for="Input.UserName" class="form-control" />
</div>
</div>
<div class="=row d-flex flex-row">
<div class="form-group col-md-6">
<label asp-for="Input.FirstName"></label>
<input asp-for="Input.FirstName" class="form-control" />
</div>
<div class="form-group col-md-6">
<label asp-for="Input.MiddleName"></label>
<input asp-for="Input.MiddleName" class="form-control" />
</div>
</div>
<div class="=row d-flex flex-row">
<div class="form-group col-md-6">
<label asp-for="Input.LastNam"></label>
<input asp-for="Input.LastNam" class="form-control" />
</div>
</div>
<div class="=row d-flex flex-row">
<div class="form-group col-md-6">
<label asp-for="Input.DateOfBirth"></label>
<input asp-for="Input.DateOfBirth" class="form-control" />
</div>
<div class="form-group col-md-6">
<label asp-for="Input.PhoneNumber"></label>
<input asp-for="Input.PhoneNumber" class="form-control" />
<span asp-validation-for="Input.PhoneNumber" class="text-danger"></span>
</div>
</div>
<div class="=row d-flex flex-row">
<div class="form-group col-md-6">
<label asp-for="Input.BuildingNo"></label>
<input asp-for="Input.BuildingNo" class="form-control" />
</div>
</div>
<div class="=row d-flex flex-row">
<div class="do-md-6">
<button id="update-profile-button" type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</form>
</div>
</div>
#section Scripts {
<partial name="_ValidationScriptsPartial" />
}
And in the Index.cshtml.cs file, I tried to save the building number in the UserAddress table as follows but it fails to enter the data into the table.
Index.cshtml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using WebApp.Models;
namespace WebApp.Areas.Identity.Pages.Account.Manage
{
public partial class IndexModel : PageModel
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
public IndexModel(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
public string BuildingNo { get; set; }
public string Username { get; set; }
[TempData]
public string StatusMessage { get; set; }
[BindProperty]
public InputModel Input { get; set; }
public class InputModel
{
[DataType(DataType.Text)]
[Display(Name = "User Name")]
public string UserName { get; set; }
[DataType(DataType.Text)]
[Display(Name = "First name")]
public string FirstName { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Middle name")]
public string MiddleName { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Last name")]
public string LastNam { get; set; }
[Display(Name = "Date of Birth")]
[DataType(DataType.Date)]
public DateTime DateOfBirth { get; set; }
[Phone]
[Display(Name = "Phone number")]
public string PhoneNumber { get; set; }
[Display(Name = "Building No:")]
[DataType(DataType.Text)]
public string BuildingNo { get; set; }
}
private async Task LoadAsync(ApplicationUser user)
{
var userName = await _userManager.GetUserNameAsync(user);
var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
Username = userName;
Input = new InputModel
{
UserName = user.UserName,
FirstName = user.FirstName,
MiddleName = user.MiddleName,
LastNam = user.LastNam,
PhoneNumber = phoneNumber,
};
}
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
await LoadAsync(user);
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
if (!ModelState.IsValid)
{
await LoadAsync(user);
return Page();
}
var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
if (Input.PhoneNumber != phoneNumber)
{
var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber);
if (!setPhoneResult.Succeeded)
{
StatusMessage = "Unexpected error when trying to set phone number.";
return RedirectToPage();
}
}
if(Input.FirstName != user.FirstName)
{
user.FirstName = Input.FirstName;
}
if (Input.MiddleName != user.MiddleName)
{
user.MiddleName = Input.MiddleName;
}
if (Input.LastNam != user.LastNam)
{
user.LastNam = Input.LastNam;
}
if (Input.DateOfBirth != user.DateOfBirth)
{
user.DateOfBirth = Input.DateOfBirth;
}
if (Input.UserName != user.UserName)
{
user.UserName = Input.UserName;
}
user.UserAddress.BuildingNo = Input.BuildingNo; // I tried to enter the building address to the UserAddress table by using this code
await _userManager.UpdateAsync(user);
await _signInManager.RefreshSignInAsync(user);
StatusMessage = "Your profile has been updated";
return RedirectToPage();
}
}
}
Please ignore the above lengthy Index.cshtml.cs code I have provided, I have commented near the only code that I used to insert the input building number to the UserAddress table. which is:
user.UserAddress.BuildingNo = Input.BuildingNo;
This is the part of view of the entry: The entry view
And this is the error I am getting when above code is run: The error message
For the record: all the fields in ApplicationUser table is updated. but this error occurs when I am trying to insert data into UserAddress table.
I am pretty user this is a very simple question for a person who knows ASP.NET core identity user very well.
I kindly request if somebody can please help me to save the input building number in another table named User Address?
Thanks in advance !!!
You can change your code like below:
First use code get current user include UserAddress:
var user = await _userManager.Users
.Include(x => x.UserAddress)
.SingleAsync(x => x.UserName== Input.UserName);
Then determine whether UserAddress exists and update it.
if (user.UserAddress == null)
{
user.UserAddress = new Models.UserAddress
{
BuildingNo = Input.BuildingNo
};
}
else
{
user.UserAddress.BuildingNo = Input.BuildingNo;
}
The whole code is like below:
public async Task<IActionResult> OnPostAsync()
{
//get the current user
var user = await _userManager.Users
.Include(x => x.UserAddress)
.SingleAsync(x => x.UserName== Input.UserName);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
if (!ModelState.IsValid)
{
await LoadAsync(user);
return Page();
}
var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
if (Input.PhoneNumber != phoneNumber)
{
var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber);
if (!setPhoneResult.Succeeded)
{
StatusMessage = "Unexpected error when trying to set phone number.";
return RedirectToPage();
}
}
if(Input.FirstName != user.FirstName)
{
user.FirstName = Input.FirstName;
}
if (Input.MiddleName != user.MiddleName)
{
user.MiddleName = Input.MiddleName;
}
if (Input.LastNam != user.LastNam)
{
user.LastNam = Input.LastNam;
}
if (Input.DateOfBirth != user.DateOfBirth)
{
user.DateOfBirth = Input.DateOfBirth;
}
if (Input.UserName != user.UserName)
{
user.UserName = Input.UserName;
}
//insert the BuildingNo
if (user.UserAddress == null)
{
user.UserAddress = new Models.UserAddress
{
BuildingNo = Input.BuildingNo
};
}
else
{
user.UserAddress.BuildingNo = Input.BuildingNo;
}
await _userManager.UpdateAsync(user);
await _signInManager.RefreshSignInAsync(user);
StatusMessage = "Your profile has been updated";
return RedirectToPage();
}

"There is no ViewData item of type 'IEnumerable' that has the key" Problem

I need to set "ManagerID" as the "id" from "Employee".(I mean ManagerID and id are linked). I write codes but have a problem. It shows items with dropdownlist correctly but when I try to apply, it says "There is no ViewData item of type 'IEnumerable' that has the key ManagerID"
View
<div class="form-group">
#Html.LabelFor(model => model.ManagerID, "ManagerID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.ManagerID, (List<SelectListItem>)ViewBag.Manager , htmlAttributes: new { #class = "control-label col-md-2" })
#Html.ValidationMessageFor(model => model.ManagerID, "", new { #class = "text-danger" })
</div>
</div>
Controller
public ActionResult Add_Department()
{
List<SelectListItem> employeeList = (from a in db.Employee.ToList()
select new SelectListItem
{
Text = a.Name + a.Surname,
Value = a.id.ToString()
}).ToList();
ViewBag.Manager = employeeList;
return View();
}
[HttpPost]
public ActionResult Add_Department(Department_Info department)
{
if (ModelState.IsValid)
{
db.Department_Info.Add(department);
db.SaveChanges();
return RedirectToAction("Main");
}
return View(department);
}
Model:
public partial class Department_Info
{
public int id { get; set; }
public string Department { get; set; }
public Nullable<int> ManID { get; set; }
}
The problem is you are not saving your Manager dropdown to ViewBag in your post action because if your request is not validated successfully then you will be returned the same page but at this time you ViewBag.Manager is null so it will cause an error.
So you need to add ViewBag.Manager SelectList also in the post action method.
[HttpPost]
public ActionResult Add_Department(Department_Info department)
{
if (ModelState.IsValid)
{
db.Department_Info.Add(department);
db.SaveChanges();
return RedirectToAction("Main");
}
List<SelectListItem> employeeList = (from a in db.Employee.ToList()
select new SelectListItem
{
Text = a.Name + a.Surname,
Value = a.id.ToString()
}).ToList();
ViewBag.Manager = employeeList;
return View(department);
}
I've also noticed that your Manager dropdown name is ManagerID while your Department_Info model doesn't have the field with the same name. Actually, this is the problem which produces the worst condition and your first problem encounters.
You need to update your Department_Info model:
public partial class Department_Info
{
public int id { get; set; }
public string Department { get; set; }
public Nullable<int> ManagerID { get; set; }
}
Or you need to change your dropdown name:
#Html.DropDownList("ManagerID", (List<SelectListItem>)ViewBag.Manager, htmlAttributes: new { #class = "control-label col-md-2" })
Hopefully, It will resolved your problem.

Upload pdf or doc into database of ASP.NET MVC-5 application

Hi,
I have been learning ASP.NET as well as doing a small project through MVC application.
My application is based on raising a purchase request for a product by an institution. It's a basic form through which all data are stored in DB.
How to add upload PDF or DOC into this coding so that the pdf quotation can be uploaded while submitting the form.
**
My Model
**
namespace sparki02.Models{
public class PRview
{
public int Id { get; set; }
[DataType(DataType.Html)]
public string Caption { get; set; }
[Required]
[DataType(DataType.ImageUrl)]
public string ImageUrl { get; set; }
[Required]
[StringLength(100)]
[Display(Name = "Supplier Name")]
public string SupplierName { get; set; }
[Required]
[StringLength(255)]
[Display(Name = "Material Name")]
public string MATName { get; set; }
[Required]
[StringLength(100)]
public string Brand { get; set; }
public PRtype PRtype { get; set; }
[Display(Name = "PR Type")]
public byte PRtypeId { get; set; }
[Required]
[Display(Name = "Unit Price")]
public double Unitprice { get; set; }}}
**
2. Controller
**
public ActionResult NewPR()
{var prtypes = _context.PRtypes.ToList();
var viewModel = new NewPRViewModel
{PRview = new PRview(),
PRtypes = prtypes};
return View("NewPR", viewModel);
}
[HttpPost]
public ActionResult Save(PRview prview, NewPRViewModel model)
{
var validImageTypes = new string[]
{
"image/gif",
"image/jpeg",
"image/pjpeg",
"image/png"
};
if (model.ImageUpload == null || model.ImageUpload.ContentLength == 0)
{
ModelState.AddModelError("ImageUpload", "This field is required");
}
else if (validImageTypes.Contains(model.ImageUpload.ContentType))
{
ModelState.AddModelError("ImageUpload", "Please choose either a GIF, JPG or PNG image.");
}
if (!ModelState.IsValid)
{
var viewModel = new NewPRViewModel
{
PRview = prview,
PRtypes = _context.PRtypes.ToList(),
Caption = model.Caption
};
return View("NewPR", viewModel);
}
if (prview.Id == 0)
_context.PRviews.Add(prview);
else
{
var prviewInDb = _context.PRviews.Single(c => c.Id == prview.Id);
prviewInDb.PRtypeId = prview.PRtypeId;
prviewInDb.MATName = prview.MATName;
prviewInDb.SupplierName = prview.SupplierName;
prviewInDb.Brand = prview.Brand;
prviewInDb.Unitprice = prview.Unitprice;
prviewInDb.ImageUrl = prview.ImageUrl;
if (model.ImageUpload != null && model.ImageUpload.ContentLength > 0)
{
var uploadDir = "~/uploads";
var imagePath = Path.Combine(Server.MapPath(uploadDir), model.ImageUpload.FileName);
var imageUrl = Path.Combine(uploadDir, model.ImageUpload.FileName);
model.ImageUpload.SaveAs(imagePath);
prview.ImageUrl = imageUrl;
}
}
_context.SaveChanges();
return RedirectToAction("Index", "PRview");
**
My View block
** Only content related to file upload
{ #model sparki02.ViewModels.NewPRViewModel
#using (Html.BeginForm("Save", "PRview", FormMethod.Post, new { enctype = "multipart/form-data" }))
{#Html.ValidationSummary(true, "Please fix the following errors.")
<div>
#Html.LabelFor(m => m.Caption)
#Html.EditorFor(m => m.Caption)
</div>
<div>
#Html.LabelFor(m => m.ImageUpload)
#Html.TextBoxFor(m => m.ImageUpload, new { type = "file" })
</div>
<button type="submit">Create</button>
<div class="form-group">
<button type="submit" class="btn btn-primary">Save</button>
</div>
<div class="form-group"> <p> #DateTime.Now</p> </div>
}
Whereas it is non-trivial to Download or View PDFs, it is relatively trivial to upload them. I used https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-2.2 as mentioned by ADyson, but only about 5% of the code is really necessary.
In your CSHTML, you must add a Form File:
<input type="file" class="custom-control-input" tabindex="0" asp-for="FileUpload.FormFile">
<label asp-for="FileUpload.FormFile" class="custom-control-label">Upload Form</label>
Your form must include
enctype="multipart/form-data"
Your class must include:
[Required]
[BindProperty]
public BufferedSingleFileUploadDb FileUpload { get; set; }
}
public class BufferedSingleFileUploadDb
{
[Required]
[Display(Name = "File")]
public IFormFile FormFile { get; set; }
}
And in your Controller, here's some code that will work, although I commented out Microsoft's AppFile suggestion. You can save the file to a filesystem, database, etc.:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> OrderEquipmentAsync(OrderEquipmentGroup orderEquipGroup)
{
if (ModelState.IsValid)
{
// save stuff here.
using (var memoryStream = new MemoryStream())
{
await orderEquipGroup.FileUpload.FormFile.CopyToAsync(memoryStream);
// Upload the file if less than 2 MB
if (memoryStream.Length < 2097152)
{
//var file = new AppFile()
//{
// Content = memoryStream.ToArray()
//};
//_dbContext.File.Add(file);
//await _dbContext.SaveChangesAsync();
}
else
{
ModelState.AddModelError("File", "The file is too large.");
}
}
My last suggestion is that you be VERY careful when uploading files to a server. As Microsoft says in their article, here are some wise guidelines: 1. use a safe filename, 2. allow only approved file extensions, 3. limit the filesize, 4. Scan the uploaded file before saving.

How to save Images to database using ASP.NET Core?

I am working on a small blog using ASP.NET Core(MVC 6) EF Visual Studio. I have trouble finding how to save images to a database. I have read about IFormfile but I do not really understand how to go about it, I am stuck. I am new to this and would love to have a little help.
I want to save the image to the post I am creating(In the same form). I, therefore, want to save it to postID. Then I need to be able to display the image, how do I do that?
You may find this useful if u need to save to database. This was a modification of https://www.mikesdotnetting.com/article/259/asp-net-mvc-5-with-ef-6-working-with-files and lots of input from k7Boys answer here MVC 6 HttpPostedFileBase?
<input type="file" name="Image" id="Imageinput">
Blog Modal Class should have Img field like;
public int BlogId{ get; set; }
...
public byte[] Img{ get; set; }
Controller;
public async Task<IActionResult> Create([Bind("BlogId,...Img")] Blog blog t, IFormFile Image)
if (ModelState.IsValid)
{
if (Image!= null)
{
if (Image.Length > 0)
//Convert Image to byte and save to database
{
byte[] p1 = null;
using (var fs1 = Image.OpenReadStream())
using (var ms1 = new MemoryStream())
{
fs1.CopyTo(ms1);
p1 = ms1.ToArray();
}
Blog.Img= p1;
}
}
_context.Add(client);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
Took me a couple of hours to get here. Now working on viewing the images in a view, am sure this will not be complex. Enjoy
Try this its working fine
controller
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,PostMode,Message,Image,AccountId,Created,Status")] Post post, IFormFile Image)
{
if (ModelState.IsValid)
{
using (var ms = new MemoryStream())
{
Image.CopyTo(ms);
post.Image = ms.ToArray();
}
_context.Add(post);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(post);
}
Display Image
#foreach (var item in Model)
{
<img class="img-responsive full-width" src="data:image/jpeg;base64,#Convert.ToBase64String(item.Image)" />
}
You can use IFormFile to save image posted from view. Below is the sample code.
public class UserProfileViewModel
{
public string UserName { get; set; }
public IFormFile UploadedImage { get; set; }
public string ImageUrl { get; set; }
}
In view simply bind it with IFormFile property like:
<img src="#Model.ImageUrl" alt="User Logo" asp-append-version="true" />
<input type="file" asp-for="UploadedImage" />
In your controller you just need to save file on server like:
var filename = ContentDispositionHeaderValue
.Parse(user.UploadedImage.ContentDisposition)
.FileName
.Trim('"');
filename = Path.Combine(webRoot, "/Content/UserProfile/", $#"\{filename}");
if (Directory.Exists(webRoot + "/Content/UserProfile/"))
{
using (FileStream fs = System.IO.File.Create(filename))
{
user.UploadedImage.CopyTo(fs);
fs.Flush();
}
}
model.ImageURL = "~/Content/Brands/" + user.UploadedImage.FileName;

mvc3 how to bind a view using HttPost

This is my first post,I am just getting my feet wet with mvc3.I have a form with 3 models in a view and I am trying to submit the form yet the 3 fields that I have come out to null once submitted in the database; this is the form. How the models are created : The main one is countries which is the one I have a problem submitting because it comes out to null
public class countries
{
public string china { get; set; }
public string japan { get; set; }
public string thailand { get; set; }
}
// I know put multiple models inside allmyplanets
public class allmyplanets
{
public IEnumerable<politcal> rankworld { get; set; }
public countries asia { get; set; }
public president names { get; set; }
}
This is how the view looks, the form is only for countries the one im trying to submit
John.Models.allmyplanets
#using (Ajax.BeginForm("planet", "earth", null, new AjaxOptions
{
UpdateTargetId = "submitted",
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST"
}))
{
#Html.TextAreaFor(x => x.asia.china)
#Html.TextAreaFor(x => x.asia.japan)
#Html.TextAreaFor(x => x.asia.thailand)
<br />
<input type="submit" name="myform" id="submitform" value="Submit Form" />
}
Thats the simple form with 3 fields now on submit I tried to capture the value and it does form a new row in the database but all 3 fields come out to null this is how i try to capture it...
public PartialViewResult planet(countries submit,string asia_china, string asia_japan, string asia_thailand)
{
submit.china = asia_china;
submit.japan = asia_japan;
submit.thailand = asia_thailand;
db.countries.Add(submit);
db.SaveChanges();
}
what can be wrong with the code that causes everything to be null? I put the under-dash because razor naming convention turns all ID's with multiple multiples to under-dashes to separate such as id="asia_china". How can this be solved?
[HttpPost]
public PartialViewResult planet(allmyplanets allplanet)
{
countries country=new countries();
allplanet.asia=country;
//save the data
}

Resources