I have three file upload control, All accepts single file but when i am getting in view all are saving as same image in my image folder -
my model is below in model i took HttpPostedFileBase type three variables and three label variable:
[NotMapped]
[DisplayName("Upload Image")]
public string ImagePath { get; set; }
[NotMapped]
public HttpPostedFileBase ImageFile { get; set; }
[NotMapped]
[DisplayName("Upload Aadhaar Card")]
public string AadhaarPathL { get; set; }
[NotMapped]
public HttpPostedFileBase AadhaarFile{get;set;}
[NotMapped]
[DisplayName("Upload PAN Card")]
public string PanPathL { get; set; }
[NotMapped]
public HttpPostedFileBase PanFile { get; set; }
In View i declared file type text bos for uploading the image :
#using (Html.BeginForm("CreateVendor", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div style="margin-left:70px;">
#Html.AntiForgeryToken()
<div class="row">
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(model => model.ImagePath)
#Html.TextBoxFor(model => model.ImageFile, new { type = "file", name = "ImageFile", id = "ImageFile",#class= "form-control" })
#Html.ValidationMessageFor(model => model.ImagePath, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(model => model.AadhaarPathL)
#Html.TextBoxFor(m => m.AadhaarFile,new { type = "file", name = "AadhaarFile", id = "AadhaarFile", #class = "form-control" })
#Html.ValidationMessageFor(model => model.AadhaarPathL, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(model => model.PanPathL)
#Html.TextBoxFor(m => m.PanFile, new { type = "file", name = "PanFile", id = "PanFile", #class = "form-control" })
#Html.ValidationMessageFor(model => model.PanPathL, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-6">
<div class="form-group">
#* Empty *#
</div>
</div>
</div>
</div>
}
And finally in View code i am getting one by one both uri and image but everytime i am getting saved same image for every image . i am stucked here
[HttpPost]
public ActionResult CreateVendor(VendorList vendorList)
{
#region Photo Image
string fileName = Path.GetFileNameWithoutExtension(vendorList.ImageFile.FileName);
string extension = Path.GetExtension(vendorList.ImageFile.FileName);
fileName = fileName + "Photo" + DateTime.Now.ToString("yymmssfff") + extension;
var uri = string.Format("{0}://{1}{2}{3}",
System.Web.HttpContext.Current.Request.Url.Scheme,
System.Web.HttpContext.Current.Request.Url.Host,
System.Web.HttpContext.Current.Request.Url.Port == 80 ? string.Empty : ":" + System.Web.HttpContext.Current.Request.Url.Port,
"/Image/" + fileName);
vendorList.ImagePath = "~/Image/" + fileName;
fileName = Path.Combine(Server.MapPath("~/Image/"), fileName);
vendorList.ImageFile.SaveAs(fileName);
vendorList.PhotoPath = fileName;
vendorList.PhotoUrl = uri;
#endregion
#region Aadhaar Image
string fileAadhaarName = Path.GetFileNameWithoutExtension(vendorList.AadhaarFile.FileName);
string extensionAadhaar = Path.GetExtension(vendorList.AadhaarFile.FileName);
fileAadhaarName = fileAadhaarName + vendorList.Email + "Aadhaar" + DateTime.Now.ToString("yymmssfff") + extensionAadhaar;
var uriAadhaar = string.Format("{0}://{1}{2}{3}",
System.Web.HttpContext.Current.Request.Url.Scheme,
System.Web.HttpContext.Current.Request.Url.Host,
System.Web.HttpContext.Current.Request.Url.Port == 80 ? string.Empty : ":" + System.Web.HttpContext.Current.Request.Url.Port,
"/Image/" + fileAadhaarName);
vendorList.AadhaarPathL = "~/Image/" + fileAadhaarName;
fileAadhaarName = Path.Combine(Server.MapPath("~/Image/"), fileAadhaarName);
vendorList.ImageFile.SaveAs(fileAadhaarName);
vendorList.AadhaarPath = fileAadhaarName;
vendorList.AadhaarUrl = uriAadhaar;
#endregion
#region Pan Image
string filePanName = Path.GetFileNameWithoutExtension(vendorList.PanFile.FileName);
string extensionPan = Path.GetExtension(vendorList.PanFile.FileName);
filePanName = filePanName + vendorList.Email + "Pan" + DateTime.Now.ToString("yymmssfff") + extensionPan;
var uriPan = string.Format("{0}://{1}{2}{3}",
System.Web.HttpContext.Current.Request.Url.Scheme,
System.Web.HttpContext.Current.Request.Url.Host,
System.Web.HttpContext.Current.Request.Url.Port == 80 ? string.Empty : ":" + System.Web.HttpContext.Current.Request.Url.Port,
"/Image/" + filePanName);
vendorList.PanPathL = "~/Image/" + filePanName;
filePanName = Path.Combine(Server.MapPath("~/Image/"), filePanName);
vendorList.ImageFile.SaveAs(filePanName);
vendorList.PanPath = filePanName;
vendorList.PanUrl = uriPan;
}
Can someone suggest what is happening here .
Related
Hello I am trying something in which I am not really an expert and only have reached so far with great help.
I have a table and a form such as this
!https://imgur.com/a/MIb112p
the table is populated by a datatable i stored in a session while the form is goes to a [httppost] method. my problem is when i click the save button the form data is being saved but not the table
my view looks like this
#using cgs.Models;
#model ConfirmOrderCustomModel
#using System.Data;
#using System.Net;
#{
ViewBag.Title = "EditProduct";
Layout = "~/Views/Shared/DashboardLayout.cshtml";
}
<div id="form-wrapper" class="page-wrapper">
<div id="overview-row" class="row">
<div class="col-lg-12">
<h1 class="page-header">Confirm Order</h1>
</div>
</div>
<div id="form-div" class="row edit-form">
#using (Html.BeginForm("ConfirmOrder", "Product", FormMethod.Post))
{
#Html.AntiForgeryToken()
#*#Html.ValidationSummary(false, "", new { #class = "text-danger" })*#
<div class="row">
<div class="col-lg-8">
<table id="calculate-table" class="rwd-table">
<tr>
<th>ID</th>
<th>Order Units</th>
<th>Total</th>
<th>Discount</th>
<th>Net</th>
</tr>
#{
if (Session["tblCart"] != null)
{
DataTable dt = (DataTable)Session["tblCart"];
foreach (DataRow row in dt.Rows)
{
<tr>
#foreach (DataColumn col in dt.Columns)
{
<td>#row[col.ColumnName]</td>
}
<td><input type="button" value="Remove" onclick="Remove(this)" /></td>
</tr>
}
}
}
</table>
</div>
</div>
<div class="row">
<div class="col-lg-8">
#Html.LabelFor(model => model.Orders.ShippingDate, new { htmlAttributes = new { #placeholder = "Shipping Date", #id = "lblShippingDate", #class = "label" } })
#Html.EditorFor(model => model.Orders.ShippingDate, new { htmlAttributes = new { #type = "date", #min = 0, #value = "", #placeholder = "Shipping Date", #name = "shippingDate", #id = "shippingDate", #required = "" } })
#Html.ValidationMessageFor(model => model.Orders.ShippingDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-lg-8">
#Html.LabelFor(model => model.Orders.OrderTotal, new { htmlAttributes = new { #placeholder = "Total", #id = "lblTotal", #class = "label" } })
#Html.EditorFor(model => model.Orders.OrderTotal, new { htmlAttributes = new { #type = "text", #min = 0, #value = "", #placeholder = "Total", #name = "total_price", #id = "total_price", #required = "" } })
#Html.ValidationMessageFor(model => model.Orders.OrderTotal, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-lg-8">
#Html.LabelFor(model => model.Orders.CustomerName, new { htmlAttributes = new { #placeholder = "Customer", #id = "lblCustomer", #class = "label" } })
#Html.EditorFor(model => model.Orders.CustomerName, new { htmlAttributes = new { #type = "text", #min = 0, #value = "", #placeholder = "Customer", #name = "cust_name", #id = "cust_name", #required = "" } })
#Html.ValidationMessageFor(model => model.Orders.CustomerName, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-lg-8">
#Html.LabelFor(model => model.Orders.CustomerPhone, new { htmlAttributes = new { #placeholder = "CustomerPhone", #id = "lblPhone", #class = "label" } })
#Html.EditorFor(model => model.Orders.CustomerPhone, new { htmlAttributes = new { #type = "text", #min = 0, #value = "", #placeholder = "Customer Phone", #name = "cust_phone", #id = "cust_phone", #required = "" } })
#Html.ValidationMessageFor(model => model.Orders.CustomerPhone, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-lg-8">
#Html.LabelFor(model => model.Orders.CustomerEmail, new { htmlAttributes = new { #placeholder = "Email", #id = "lblEmail", #class = "label" } })
#Html.EditorFor(model => model.Orders.CustomerEmail, new { htmlAttributes = new { #type = "text", #min = 0, #value = "", #placeholder = "Email", #name = "cust_email", #id = "cust_email", #required = "" } })
#Html.ValidationMessageFor(model => model.Orders.CustomerEmail, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-lg-8">
#Html.LabelFor(model => model.Orders.DeliveryAddress, new { htmlAttributes = new { #placeholder = "Delivery Address", #id = "lblAddress", #class = "label" } })
#Html.EditorFor(model => model.Orders.DeliveryAddress, new { htmlAttributes = new { #type = "text", #min = 0, #value = "", #placeholder = "Address", #name = "cust_address", #id = "cust_Address", #required = "" } })
#Html.ValidationMessageFor(model => model.Orders.DeliveryAddress, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-offset-4 col-md-4">
<button id="btnSave" name="action" value="confirm">Confirm Order</button>
</div>
</div>
}
</div>
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
jQuery(document).ready(function() {
setTimeout(function() {
var sum1 = 0;
$("#calculate-table tr").not(':first').each(function () {
sum1 += getnum($(this).find("td:eq(4)").text());
function getnum(t) {
if (isNumeric(t)) {
return parseInt(t, 10);
}
return 0;
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
}
});
$("#total_price").val(sum1);
}, 1000);
});
function Remove(button) {
//Determine the reference of the Row using the Button.
var row = $(button).closest("TR");
var name = $("TD", row).eq(0).html();
if (confirm("Do you want to delete: " + name)) {
//Get the reference of the Table.
var table = $("#calculate-table")[0];
//Delete the Table row using it's Index.
table.deleteRow(row[0].rowIndex);
}
};
$("body").on("click", "#btnSave", function () {
//Loop through the Table rows and build a JSON array.
var orderProducts = new Array();
$("#calculate-table tr").each(function () {
var row = $(this);
var products = {};
products.ProductID = row.find("td").eq(0).html();
products.OrderUnits = row.find("td").eq(1).html();
products.TotalSum = row.find("td").eq(2).html();
products.DiscountVal = row.find("td").eq(3).html();
products.NetSum = row.find("td").eq(4).html();
orderProducts.push(products);
});
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Product/ConfirmOrder",
data: JSON.stringify(orderProducts),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
}
});
});
</script>
and my actionresult like this
[HttpPost]
public JsonResult ConfirmOrder(ConfirmOrderCustomModel model)
{
using(dbcontext = new CDBContext())
{
dbcontext.Orders.Add(new Model.Orders
{
ShippingDate = model.Orders.ShippingDate,
OrderTotal = model.Orders.OrderTotal,
CustomerName = model.Orders.CustomerName,
CustomerPhone = model.Orders.CustomerPhone,
CustomerEmail = model.Orders.CustomerEmail,
DeliveryAddress = model.Orders.DeliveryAddress,
OrderStatus = true
});
dbcontext.SaveChanges();
int id = dbcontext.Orders.Max(odr => odr.ID);
DataTable dt = (DataTable)Session["tblCart"];
List<DataRow> list = new List<DataRow>(dt.Select());
foreach (var item in model.SalesModel)
{
dbcontext.OrderProducts.Add(new OrderProducts
{
OrderUnits = item.OrderUnits,
TotalSum = item.TotalSum,
DiscountVal = item.DiscountVal,
NetSum = item.NetSum,
ProductID = item.ProductID,
OrderID = id
});
dbcontext.SaveChanges();
}
return Json(new
{
redirectUrl = Url.Action("Dashboard", "Admin"),
isRedirect = true
});
}
}
any help is appreciated
I am quite new to MVC and coding, so apologies if I don't bring it to the point. I am encountering a weird issue that I somehow cannot manage to solve:
I want to submit a form that includes an image along with other values, such as user name, user ID, timestamp, etc. and write it into a table (SQL); now I can get the image as byte to the DB and I can get the form submitted to the DB, but for some reason I cannot get it done at the same time, so it's either the image/file or the form. The error I encounter is the following:
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.
View Model:
namespace errandomWeb.Models
{
public class PhotoCompetition
{
public int ID { get; set; }
public string UserID { get; set; }
public string FirstName { get; set; }
public string Email { get; set; }
public byte[] CompetitionPicture { get; set; }
//[Required]
[Display(Name = "by checking this box I accept the Terms & Conditions")]
public bool TermsAndConditionsAccepted { get; set; }
public DateTime TimeStamp { get; set; }
}
}
Controller (getting error message):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadCompetitionPicture(PhotoCompetition model)
{
string croppedImage = Request.Form["photoCompetitionCroppedPicture"];
byte[] imageBytes = Convert.FromBase64String(croppedImage);
var userId = User.Identity.GetUserId();
var participation = new PhotoCompetition
{
CompetitionPicture = imageBytes,
UserID = User.Identity.GetUserId(),
FirstName = "testcase",
Email = User.Identity.GetUserName(),
TermsAndConditionsAccepted = true,
TimeStamp = DateTime.UtcNow.ToUniversalTime(),
};
DB.PhotoCompetition.Add(participation);
DB.SaveChanges();
return View("Edit");
}
}
Controller (working for image, but not the form...):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadCompetitionPicture()
{
string croppedImage = Request.Form["photoCompetitionCroppedPicture"];
byte[] imageBytes = Convert.FromBase64String(croppedImage);
var userId = User.Identity.GetUserId();
var participation = new PhotoCompetition
{
CompetitionPicture = imageBytes,
UserID = User.Identity.GetUserId(),
FirstName = "testcase",
Email = User.Identity.GetUserName(),
TermsAndConditionsAccepted = true,
TimeStamp = DateTime.UtcNow.ToUniversalTime(),
};
DB.PhotoCompetition.Add(participation);
DB.SaveChanges();
return View("Edit");
}
}
View:
#model errandomWeb.Models.PhotoCompetition
#{
ViewBag.Title = "Become Our Model";
}
<div id="photoCompetitionContainer" class="manageContainer">
<div id="photoCompetitionHeaderSection" class="manageHeaderSection">
<h1 id="photoCompetitionHeaderTitle" class="manageHeaderTitle">
#ViewBag.Title
</h1>
<img id="photoCompetitionHeaderProfilePicture" class="manageHeaderProfilePicture" src="#Url.Action("UserPicture", "Manage")" />
<p id="photoCompetitionHeaderPersonalizationGeneric" class="manageHeaderPersonalization">
Hello
</p>
<p id="photoCompetitionHeaderPersonalizationName" class="manageHeaderPersonalization">
#Html.TextBoxFor(m => m.FirstName, new { #id = "photoCompetitionHeaderUserName", #class = "manageHeaderUserName", #placeholder = "Stranger", #disabled = true })
</p>
</div>
#Html.Partial("_ProfileLogout")
<div id="photoCompetitionContextSection" class="manageContextSection">
<p id="photoCompetitionContext" class="manageContext">
Want to become our model?
</p>
</div>
<div id="photoCompetitionValidationSection" class="manageValidation">
#Html.ValidationSummary("", new { #id = "photoCompetitionValidation", #class = "manageValidation" })
</div>
<section id="photoCompetition" class="manageForm">
#using (Html.BeginForm("UploadCompetitionPicture", "errandom", FormMethod.Post, new { #id = "photoCompetitionForm", #class = "form-horizontal", #role = "form", #enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div id="photoCompetitionSection" class="manageSection">
<p id="photoCompetitionSectionTitle" class="manageSectionTitle">
Upload your picture and be selected as our model!
</p>
#Html.HiddenFor(m => m.UserID)
#Html.HiddenFor(m => m.Email)
#Html.HiddenFor(m => m.FirstName)
#Html.HiddenFor(m => m.TimeStamp)
<div id="photoCompetitionProfilePictureArea" class="manageArea row">
#Html.LabelFor(m => m.CompetitionPicture, new { #id = "photoCompetitionProfilePictureLabel", #class = "manageLabel col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-1 col-md-3 col-lg-offset-1 col-lg-4" })
<a id="photoCompetitionProfilePictureSelectionButton" class="manageField col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset0 col-md-7 col-lg-offset-0 col-lg-6" href="#">
select a file...
</a>
#Html.TextBoxFor(m => m.CompetitionPicture, new { #id = "photoCompetitionProfilePictureField", #class = "manageField col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-0 col-md-7 col-lg-offset-0 col-lg-6", #type = "file", #style = "display: none" })
</div>
<div id="photoCompetitionTermsAndConditionsArea" class="manageArea row">
#Html.CheckBoxFor(m => m.TermsAndConditionsAccepted, new { #id = "photoCompetitionTermsAndConditionsField", #class = "photoCompetitionTermsAndConditionsField" })
#Html.LabelFor(m => m.TermsAndConditionsAccepted, new { #id = "photoCompetitionTermsAndConditionsLabel", #class = "photoCompetitionTermsAndConditionsLabel" })
#Html.ValidationMessageFor(m => m.TermsAndConditionsAccepted, "", new { #id = "photoCompetitionTermsAndConditionsValidation", #class = "manageValidation col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-4 col-md-7 col-lg-offset-5 col-lg-6" })
</div>
<script>
jQuery("#photoCompetitionProfilePictureSelectionButton").click(function () {
$("#photoCompetitionProfilePictureField").click();
});
</script>
<script>
$("#photoCompetitionProfilePictureField").change(function () {
var fullFileName = $("#photoCompetitionProfilePictureField").val()
$("#photoCompetitionProfilePictureSelectionButton").html(fullFileName.substr(fullFileName.lastIndexOf('\\') + 1));
});
</script>
<div id="photoCompetitionCroppingArea" class="manageArea row">
<img id="photoCompetitionOriginal" class="photoCompetitionImage" src="" alt="" style="display: none" />
<canvas id="photoCompetitionCropped" class="photoCompetitionImage" height="5" width="5"></canvas>
</div>
<div id="photoCompetitionButtonArea" class="manageArea row">
<input id="photoCompetitionButtonCrop" class="manageButton col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-1 col-md-10 col-lg-offset-1 col-lg-10" type="button" value="Crop" style="display: none" />
<input id="photoCompetitionButtonUpload" class="manageButton col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-1 col-md-10 col-lg-offset-1 col-lg-10" type="submit" value="Save" style="display: none" />
<input id="photoCompetitionCropX" class="photoCompetitionData" name="photoCompetitionCropX" type="hidden" />
<input id="photoCompetitionCropY" class="photoCompetitionData" name="photoCompetitionCropY" type="hidden" />
<input id="photoCompetitionCropW" class="photoCompetitionData" name="photoCompetitionCropW" type="hidden" />
<input id="photoCompetitionCropH" class="photoCompetitionData" name="photoCompetitionCropH" type="hidden" />
<input id="photoCompetitionCroppedPicture" class="photoCompetitionData" name="photoCompetitionCroppedPicture" type="hidden" />
</div>
</div>
}
</section>
<div id="photoCompetitionReturnToMenuSection" class="manageReturnToMenuSection">
#Html.ActionLink("Return to Menu", "Index", "", htmlAttributes: new { #id = "photoCompetitionReturnToMenuButton", #class = "manageReturnToMenuButton" })
</div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/tapmodo/Jcrop/master/js/jquery.Jcrop.min.js"></script>
<script type="text/javascript">
$(function () {
if ($('#photoCompetitionCroppingArea').width() > 700) {
$('#photoCompetitionProfilePictureField').change(function () {
$('#photoCompetitionOriginal').hide();
var reader = new FileReader();
reader.onload = function (e) {
$('#photoCompetitionOriginal').show();
$('#photoCompetitionOriginal').attr("src", e.target.result);
$('#photoCompetitionOriginal').Jcrop({
onChange: SetCoordinates,
onSelect: SetCoordinates,
aspectRatio: 1,
boxWidth: 600,
addClass: 'photoCompetitionCropping'
});
}
reader.readAsDataURL($(this)[0].files[0]);
});
}
else {
$('#photoCompetitionProfilePictureField').change(function () {
$('#photoCompetitionOriginal').hide();
var reader = new FileReader();
reader.onload = function (e) {
$('#photoCompetitionOriginal').show();
$('#photoCompetitionOriginal').attr("src", e.target.result);
$('#photoCompetitionOriginal').Jcrop({
onChange: SetCoordinates,
onSelect: SetCoordinates,
aspectRatio: 1,
boxWidth: 250,
addClass: 'photoCompetitionCropping'
});
}
reader.readAsDataURL($(this)[0].files[0]);
});
}
$('#photoCompetitionButtonCrop').click(function () {
var x1 = $('#photoCompetitionCropX').val();
var y1 = $('#photoCompetitionCropY').val();
var height = $('#photoCompetitionCropH').val();
var width = $('#photoCompetitionCropW').val();
var canvas = $("#photoCompetitionCropped")[0];
var context = canvas.getContext('2d');
var img = new Image();
img.onload = function () {
canvas.height = height;
canvas.width = width;
context.drawImage(img, x1, y1, width, height, 0, 0, width, height);
var image = canvas.toDataURL().replace(/^data:image\/[a-z]+;base64,/, "");
$('#photoCompetitionCroppedPicture').val(image);
$('#photoCompetitionButtonUpload').show();
$('#photoCompetitionCropped').hide();
$('#photoCompetitionButtonCrop').hide();
};
img.src = $('#photoCompetitionOriginal').attr("src");
});
});
function SetCoordinates(c) {
$('#photoCompetitionCropX').val(c.x);
$('#photoCompetitionCropY').val(c.y);
$('#photoCompetitionCropW').val(c.w);
$('#photoCompetitionCropH').val(c.h);
$('#photoCompetitionButtonCrop').show();
};
</script>
}
If anyone has an idea on how I could submit the image while also submitting the other properties I would highly appreciate guidance/advice! Thank you!
I finally got it done. Here's the updated controller code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadCompetitionPicture([Bind(Exclude = "CompetitionPicture")]PhotoCompetition model)
{
string croppedImage = Request.Form["photoCompetitionCroppedPicture"];
byte[] imageBytes = Convert.FromBase64String(croppedImage);
var userId = User.Identity.GetUserId();
var participation = new PhotoCompetition
{
UserID = User.Identity.GetUserId(),
FirstName = "Ken",
Email = User.Identity.GetUserName(),
TermsAndConditionsAccepted = true,
TimeStamp = DateTime.UtcNow.ToUniversalTime(),
};
participation.CompetitionPicture = imageBytes;
DB.PhotoCompetition.Add(participation);
DB.SaveChanges();
return View("Edit");
}
I guess, what made the difference is excluding the picture in the first place, then submitting all other fields and after that adding the picture separately. Not sure why, but glad I figured it out.
Ok So I have been searching all over have come to this little bit of code and got almost everything to work. I can upload an image and save it to the folder that was created. I can save the the other values pass to the database as well. My problem now is that i want to save the file path to the data base so i can call it to display the image on another page. For some reason it will only save the image's name that is being uploaded and not the path.
When i debug it and see what all is getting passed, when i add a watch to
file.SaveAs(pathLoc);
Expression has been evaluated and has no value void
Here is the code I've beed using
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ImageInfo info, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file != null)
{
var pic = Path.GetFileName(file.FileName);
var pathLoc = Path.Combine(Server.MapPath("~/Uploads/") + pic);
file.SaveAs(pathLoc);
info.ImagePath = file.FileName;
db.SaveChanges();
}
return RedirectToAction("Index");
}
return View(info);
}
View
<h2>Create</h2>
#using (Html.BeginForm("Create", "ImageInfoes", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="form-horizontal">
<h4>ImageInfo</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ImageName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ImageName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ImageName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ImageSize, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ImageSize, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ImageSize, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ImagePath, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input id="ImagePath" title="Upload a product image" type="file" name="file" />
</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>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Model
public partial class ImageInfo
{
public byte id { get; set; }
public string ImageName { get; set; }
public Nullable<long> ImageSize { get; set; }
public string ImagePath { get; set; }
}
Anything would be help full.
If you want, full path you need to combine file path and file name both.
Console.WriteLine(Path.Combine(System.Reflection.Assembly.GetExecutingAssembly().Location, System.IO.Path.GetRandomFileName()));
C:\Users\02483695\Documents\Visual Studio
2015\Projects\ConsoleApplication5\Cons
oleApplication5\bin\Debug\ConsoleApplication5.exe\tv1k1uev.jsq
Also below you may find a sample about file, file directory, file path and file extension.
System.IO.FileInfo fileInfo = new FileInfo("filename.file");
var fileDirectory = fileInfo.DirectoryName;
var fileName = fileInfo.Name;
var fileExtension = fileInfo.Extension;
var filePathandFileNameBoth = fileInfo.FullName;
Console.WriteLine("filePathandFileNameBoth: ");
Console.WriteLine(filePathandFileNameBoth);
Console.WriteLine("-");
Console.WriteLine("fileDirectory:");
Console.WriteLine(fileDirectory);
Console.WriteLine("-");
Console.WriteLine("fileName:");
Console.WriteLine(fileName);
Console.WriteLine("-");
Console.WriteLine(filePathandFileNameBoth == fileDirectory + "\\" + fileName ? fileExtension : "I'm totally wrong");
Console.ReadLine();
as a result:
I would like to put uploadify in the website I'm making so that I can see the progress of the files that being attach. So I search on how to do that, I know I'm doing something wrong that's why it's not working(the progress doesn't show). Please help me, I'm new with this kind of stuff. Thank you. Here's my controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(EmailFormModel model, IEnumerable<HttpPostedFileBase> files)
{
if (ModelState.IsValid)
{
List<string> paths = new List<string>();
foreach (var file in files)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/uploads"), fileName);
file.SaveAs(path);
paths.Add(path);
}
}
var message = new MailMessage();
foreach (var path in paths)
{
var fileInfo = new FileInfo(path);
var memoryStream = new MemoryStream();
using (var stream = fileInfo.OpenRead())
{
stream.CopyTo(memoryStream);
}
memoryStream.Position = 0;
string fileName = fileInfo.Name;
message.Attachments.Add(new Attachment(memoryStream, fileName));
}
//Rest of business logic here
string EncodedResponse = Request.Form["g-Recaptcha-Response"];
bool IsCaptchaValid = (ReCaptcha.Validate(EncodedResponse) == "True" ? true : false);
if (IsCaptchaValid)
{
var body = "<p>Email From: {0} ({1})</p><p>Subject: {2} </p><p>Message:</p><p>{3}</p>";
message.To.Add(new MailAddress("***#gmail.com")); // replace with valid value
message.From = new MailAddress("***#ymailcom"); // replace with valid value
message.Subject = "Your email subject";
message.Body = string.Format(body, model.FromName, model.FromEmail, model.FromSubject, model.Message);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = "***#gmail.com", // replace with valid value
Password = "***" // replace with valid value
};
smtp.Credentials = credential;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
await smtp.SendMailAsync(message);
ViewBag.Message = "Your message has been sent!";
ModelState.Clear();
return View("Index");
}
}
else
{
TempData["recaptcha"] = "Please verify that you are not a robot!";
}
}
return View(model);
}
public ActionResult Upload()
{
var file = Request.Files["Filedata"];
string savePath = Server.MapPath(("~/uploads") + file.FileName);
file.SaveAs(savePath);
return Content(Url.Content(("~/uploads") + file.FileName));
}
And here's the script that I add to my _Layout.cshtml :
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery-1.10.2.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Content/UploadifyContent/jquery.uploadify.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Content/UploadifyContent/jquery.uploadify.min.js")"></script>
<link rel="stylesheet" type="text/css" href="#Url.Content("~/Content/UploadifyContent/uploadify.css")" />
<script type="text/javascript">
$(function () {
$('#file_upload').uploadify({
'swf': "#Url.Content("~/Content/UploadifyContent/uploadify.swf")",
'cancelImg': "#Url.Content("~/Content/UploadifyContent/uploadify-cancel.png")",
'uploader': "#Url.Action("Upload", "Home")",
'onUploadSuccess': function (file, data, response) {
$("#uploaded").append("<img src='" + data + "' alt='Uploaded Image' />");
}
});
});
</script>
And here's my view:
#using (Html.BeginForm("Index", "Home", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="col-md-4">
<div class="contact_form block">
<div class="row">
<div class="col-md-12 col-sm-12">
<div id="note"></div>
</div>
</div>
<div id="fields">
<div class="col-md-12 col-sm-6">
#Html.LabelFor(m => m.FromName)
#Html.TextBoxFor(m => m.FromName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromName, null, new { #class = "text-danger" })
</div>
<div class="col-md-12 col-sm-6">
#Html.LabelFor(m => m.FromEmail)
#Html.TextBoxFor(m => m.FromEmail, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromEmail, null, new { #class = "text-danger" })
</div>
<div class="clear"></div>
<div class="col-md-12 col-sm-6">
#Html.LabelFor(m => m.FromSubject)
#Html.TextBoxFor(m => m.FromSubject, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromSubject, null, new { #class = "text-danger" })
</div>
<div class="col-md-12 col-sm-6">
<form action="" method="post" enctype="multipart/form-data">
<label for="file1">Attachments</label>
<input type="file" name="files" id="file1" multiple />
</form>
<div id="uploaded"></div>
</div>
<div class="col-md-12">
#Html.LabelFor(m => m.Message)
#Html.TextAreaFor(m => m.Message, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Message, null, new { #class = "text-danger" })
</div>
<div class="col-md-12">
<div>
#if ((TempData["recaptcha"]) != null)
{
<p>#TempData["recaptcha"]</p>
}
</div>
<div class="g-recaptcha" data-sitekey="6LfVHx8TAAAAAMTDxxQrHDCxO1SyXf1GgbgNBZ5a"></div>
</div>
<div class="col-md-12"><input class="shortcode_button" type="submit" value="Send"></div>
</div>
</div>
</div>
}
Hi im making a shopping cart and i need to register the client, in the database i have two tables one for client and one for users in a one-one relationship in my asp.net mvc i create 2 models one for the client and other for the user, and a clientViewModel how join the two models(client & users) in the view i put a #using(Html.BeginForm) where i request the client & users attributes but when i submit the form to the controller all values are null
This is the ClientViewModel
namespace TiendaRocio.Models
{
public class ClienteViewModel
{
public Cliente Cliente { get; set; }
public Usuarios Usuarios { get; set; }
}
}
This is the view
#model TiendaRocio.Models.ClienteViewModel
#{
ViewBag.Title = "Registrar";
}
<header class="page-header">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header icono">
<a class="navbar-brand" href="~/">
<span class="glyphicon glyphicon-user" aria-hidden="true"> </span>
</a>
</div>
<h1>Registro<small> de usuarios</small></h1>
</div>
</nav>
</header>
#using (Html.BeginForm("Registro", "Ingresar", FormMethod.Post))
{
<div class="form-group">
<label>Nombre</label>
#Html.TextBoxFor(model => model.Cliente.nombre_cliente, new { #class = "form-control", placeholder = "Ingrese aqui su Nombre ", maxlength = 50 })
</div>
<div class="form-group">
<label>Apellidos</label>
#Html.TextBoxFor(model => model.Cliente.apellidos, new { #class = "form-control", placeholder = "Ingrese aqui sus apellidos", maxlength = 50 })
</div>
<div class="form-group">
<label>Dirección</label>
#Html.TextBoxFor(model => model.Cliente.direccion, new { #class = "form-control", placeholder = "Ingrese aqui su Dirección", maxlength = 50 })
</div>
<div class="form-group">
<label>Ciudad</label>
#Html.TextBoxFor(model => model.Cliente.ciudad, new { #class = "form-control", placeholder = "Ciudad", maxlength = 50 })
</div>
<div class="form-group">
<label>Estado</label>
#Html.TextBoxFor(model => model.Cliente.estado, new { #class = "form-control", placeholder = "Estado", maxlength = 50 })
</div>
<div class="form-group">
<label>Codigo Postal</label>
#Html.TextBoxFor(model => model.Cliente.codigo_postal, new { #class = "form-control", placeholder = "Ingrese aqui su Codigo Postal", maxlength = 50 })
</div>
<div class="form-group">
<label>Telefono</label>
#Html.TextBoxFor(model => model.Cliente.telefono, new { #class = "form-control", placeholder = "Ingrese aqui su Telefono", maxlength = 50 })
</div>
<div class="form-group">
<label>Nombre de Usuario</label>
#Html.TextBoxFor(model => model.Usuarios.nombre_usuario, new { #class = "form-control", placeholder = "Ingrese aqui su Nobre de Usuario", maxlength = 50 })
</div>
<div class="form-group">
<label>Contraseña</label>
#Html.TextBoxFor(model => model.Usuarios.contraseña, new { #class = "form-control", placeholder = "Ingrese aqui su contraseña", maxlength = 50 })
</div>
<div class="form-group">
<button type="submit" class="btn btn-danger">Registrar</button>
</div>
}
<div>
#Html.ActionLink("Regresar","Index","Home")
</div>
And this is the controller
public ActionResult Registro(string Nombre_Cliente,string Apellidos,string Direccion,string Ciudad,string Estado,string Codigo_Postal,string Telefono, string Nombre_Usuario, string Contraseña)
{
if (ModelState.IsValid)
{
if (modelo.registrar(new Usuarios { nombre_usuario = Nombre_Usuario, contraseña = Contraseña, permisos = 0 }))
{
if (cm.registrar(new Cliente { nombre_cliente = Nombre_Cliente, apellidos = Apellidos, direccion = Direccion, ciudad = Ciudad, estado = Estado, codigo_postal = Codigo_Postal, telefono = Telefono }))
{
return new RedirectResult("~/Home", false);
}
return new RedirectResult("Registrar", false);
}
else
{
return new RedirectResult("Registrar", false);
}
}
else
{
return new RedirectResult("Registrar", false);
}
}
Change yor controller method to
[HpptPost]
public ActionResult Registro(ClienteViewModel model)
{
....
}
and the properties of the model will be correctly bound. You generating controls for your model, so post it back!. If you inspect the html your generating you will see elements such as
<input type="text" name="Cliente.nombre_cliente" .../>
not name="nombre_cliente" so there is no posted value that would match string Nombre_Cliente
Side note: Rather than adding attributes such as maxlength = 50, use validation attributes (e.g. [StringLength] on your model properties so that you get both server and client side validation in conjunction with #Html.ValidatinMessageFor()