Cannot pass an HttpPostedFileBase from View to Action Method - asp.net-mvc

In my view, I have an image element as follows:
<img id="ImageDisplay" class="img-thumbnail" width="280" height="280"
src="#Url.Action("GetFileFromHttpPostedFile", "Image", new { File = Model.File })"/>
When I debug my code, I can see that my Model.File is not null. But when I pass it to the action method, the action method receives the parameter as null. Here is my action method:
public FileContentResult GetFileFromHttpPostedFile(HttpPostedFileBase File)
{
byte[] imageData = new byte[File.ContentLength];
File.InputStream.Read(imageData, 0, File.ContentLength);
return GetFileFromData(imageData, File.ContentType);
}
Am I missing something? Can we not pass an HttpPostedFileBase to a method? Help please.
Edit:
I also have the following element in the view that allows the user to populate Model.File property:
<input type="file" name="File" id="File" onchange="loadFile(event)" />
loadFile(event) simply shows a preview of the picture on the view.
Edit 2: Here is the full code for the view:
#model MyProject.Models.ViewModels.ChangeProfileModel
#{
ViewBag.Title = "Change Your Profile";
}
<script>
$(document).ready(function () {
$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);
function updateCount() {
var cs = [500 - $(this).val().length];
$('#characters').text(cs);
}
});
var loadFile = function (event) {
var output = document.getElementById('ImageDisplay');
if (output != null) {
output.src = URL.createObjectURL(event.target.files[0]);
}
};
</script>
<h2>Change Your Profile Info</h2>
#using (Html.BeginForm("ChangeProfile", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
if (ViewBag.ChangesSaved == true)
{
<div class="alert alert-success">
Your changes have been saved successfully!
×
</div>
}
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.City, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.City, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.City, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Country, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Country, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Country, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Select an Image </label>
<div class="col-md-10">
<input type="file" name="File" id="File" onchange="loadFile(event)" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2"></label>
<div class="col-md-10">
#if (Model.File == null)
{
<img id="ImageDisplay" class="img-thumbnail" width="280" height="280"
src="#Url.Action("GetImageByUser", "Image", new { id = Model.Id })"/>
}
else
{
<img id="ImageDisplay" class="img-thumbnail" width="280" height="280"
src="#Url.Action("GetFileFromHttpPostedFile", "Image", new { File = Model.File })"/>
}
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.About, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextAreaFor(m => m.About, new { #class = "form-control", #rows = "5", #maxlength = 500 })
<span id="characters" style="color:#999;">500</span> <span style="color:#999;">characters left</span>
#Html.ValidationMessageFor(model => model.About, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
#Html.ActionLink("Cancel", "Index", "Manage", null, new { #class = "btn btn-default" })
</div>
</div>
</div>
}
In my HomeController, I have the following methods:
public ActionResult ChangeProfile()
{
var userId = User.Identity.GetUserId();
var loggedInUser = UserManager.FindById(userId);
ChangeProfileModel viewModel = new ChangeProfileModel
{
Id = userId,
City = loggedInUser.City,
Country = loggedInUser.Country,
About = loggedInUser.About
};
return View(viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ChangeProfile(ChangeProfileModel viewModel)
{
if (!ModelState.IsValid)
{
return View(viewModel);
}
var userId = User.Identity.GetUserId();
var loggedInUser = UserManager.FindById(userId);
byte[] imageData = null;
if (viewModel.File != null)
{
imageData = new byte[viewModel.File.ContentLength];
viewModel.File.InputStream.Read(imageData, 0, viewModel.File.ContentLength);
}
_aspNetUserRepository.EditUserInfo(userId, viewModel.City, viewModel.Country, viewModel.About,
imageData, (viewModel.File == null) ? null: viewModel.File.ContentType);
ViewBag.ChangesSaved = true;
return View(viewModel);
}
Lastly, here is my last relevant action method inside ImageController:
public FileContentResult GetFileFromHttpPostedFile(HttpPostedFileBase File)
{
byte[] imageData = new byte[File.ContentLength];
File.InputStream.Read(imageData, 0, File.ContentLength);
return GetFileFromData(imageData, File.ContentType);
}

Related

How Send Multiple Rows by using multiple models in ASP.NET MVC

public partial class Sale
{
public int Sale_id { get; set; }
public string Order_No { get; set; }
public string Customer_name { get; set; }
public string Customer_phone { get; set; }
public string Customer_address { get; set; }
public string Payment_method { get; set; }
public double Total_amout { get; set; }
public bool Status_bit { get; set; }
public string Created_by { get; set; }
public System.DateTime Created_date { get; set; }
public string Modified_by { get; set; }
public System.DateTime Modified_date { get; set; }
}
public partial class SalesDetail
{
public int Sales_detail_id { get; set; }
public string Order_No_cp { get; set; }
public int Product_id { get; set; }
public double Unit_price { get; set; }
public int Quantity { get; set; }
public double LineTotal { get; set; }
public virtual Product Product { get; set; }
}
I Combined two model (Sales & SalesDetail)
public class Combined
{
public virtual Sale MCombined_Sales { get; set; }
public virtual SalesDetail MCombined_SalesDetail { get; set; }
}
Controller
public ActionResult Client()
{
Session["SysDateTime"] = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
Session["CrruntUser"] = "Testing";
ViewBag.Product_id = new SelectList(db.Products, "Product_id", "Product_name");
return View();
}
[HttpPost]
public ActionResult Add(Combined model)
{
if (ModelState.IsValid == true)
{
var MCombined_Sales = new Sale
{
Order_No = model.MCombined_Sales.Order_No,
Customer_name = model.MCombined_Sales.Customer_name,
Customer_phone = model.MCombined_Sales.Customer_phone,
Customer_address = model.MCombined_Sales.Customer_address,
Payment_method = model.MCombined_Sales.Payment_method,
Total_amout = model.MCombined_Sales.Total_amout,
Status_bit = model.MCombined_Sales.Status_bit,
Created_by = model.MCombined_Sales.Created_by,
Created_date = model.MCombined_Sales.Created_date,
Modified_by = model.MCombined_Sales.Modified_by,
Modified_date = model.MCombined_Sales.Modified_date,
};
var MCombined_SalesDetail = new SalesDetail
{
Order_No_cp = model.MCombined_SalesDetail.Order_No_cp,
Product_id = model.MCombined_SalesDetail.Product_id,
Unit_price = model.MCombined_SalesDetail.Unit_price,
Quantity = model.MCombined_SalesDetail.Quantity,
LineTotal = model.MCombined_SalesDetail.LineTotal,
};
using (var context = new Entities())
{
context.Sales.Add(MCombined_Sales);
MCombined_Sales.Sale_id = MCombined_Sales.Sale_id;
context.SalesDetails.Add(MCombined_SalesDetail);
context.SaveChanges();
ModelState.Clear();
}
}
return View();
}
View ( With using namespace:- #model ASH_POS.Models.Merge.Combined)
#using (Html.BeginForm(new { #id = "registerFormId", #class = "form-horizontal", role = "form" })) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="card">
<h4 class="text-center">Sale</h4>
<div id="Detail" class="row visually-hidden">
<div class="col">
<div class="form-group">
#Html.LabelFor(model => model.MCombined_Sales.Status_bit, htmlAttributes: new { #class = "control-label " })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.MCombined_Sales.Status_bit)
#Html.ValidationMessageFor(model => model.MCombined_Sales.Status_bit, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="col">
<div class="form-group">
#Html.LabelFor(model => model.MCombined_Sales.Created_by, htmlAttributes: new { #class = "control-label " })
<div class="col-md-10">
#Html.EditorFor(model => model.MCombined_Sales.Created_by, new { htmlAttributes = new { #class = "form-control", #Value = Session["CrruntUser"], #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.MCombined_Sales.Created_by, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col">
<div class="form-group">
#Html.LabelFor(model => model.MCombined_Sales.Created_date, htmlAttributes: new { #class = "control-label " })
<div class="col-md-10">
#Html.EditorFor(model => model.MCombined_Sales.Created_date, new { htmlAttributes = new { #class = "form-control", #Value = Session["SysDateTime"], #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.MCombined_Sales.Created_date, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col">
<div class="form-group">
#Html.LabelFor(model => model.MCombined_Sales.Modified_by, htmlAttributes: new { #class = "control-label " })
<div class="col-md-10">
#Html.EditorFor(model => model.MCombined_Sales.Modified_by, new { htmlAttributes = new { #class = "form-control", #Value = Session["CrruntUser"], #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.MCombined_Sales.Modified_by, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col">
<div class="form-group">
#Html.LabelFor(model => model.MCombined_Sales.Modified_date, htmlAttributes: new { #class = "control-label " })
<div class="col-md-10">
#Html.EditorFor(model => model.MCombined_Sales.Modified_date, new { htmlAttributes = new { #class = "form-control", #Value = Session["SysDateTime"], #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.MCombined_Sales.Modified_date, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="card-title">
<div class="form-group">
#Html.LabelFor(model => model.MCombined_Sales.Order_No, htmlAttributes: new { #class = "control-label " })
<div class="col-md-10">
#Html.EditorFor(model => model.MCombined_Sales.Order_No, new { htmlAttributes = new { #class = "form-control", #required = true, #Value = "1500" } })
#Html.ValidationMessageFor(model => model.MCombined_Sales.Order_No, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col">
<div class="form-group">
#Html.LabelFor(model => model.MCombined_Sales.Customer_name, htmlAttributes: new { #class = "control-label " })
<div class="col-md-10">
#Html.EditorFor(model => model.MCombined_Sales.Customer_name, new { htmlAttributes = new { #class = "form-control", #required = true, #Value = "N/A" } })
#Html.ValidationMessageFor(model => model.MCombined_Sales.Customer_name, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col">
<div class="form-group">
#Html.LabelFor(model => model.MCombined_Sales.Customer_phone, htmlAttributes: new { #class = "control-label " })
<div class="col-md-10">
#Html.EditorFor(model => model.MCombined_Sales.Customer_phone, new { htmlAttributes = new { #class = "form-control", #Value = "N/A" } })
#Html.ValidationMessageFor(model => model.MCombined_Sales.Customer_phone, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col">
<div class="form-group">
#Html.LabelFor(model => model.MCombined_Sales.Customer_address, htmlAttributes: new { #class = "control-label" })
<div class="col-md-10">
#Html.EditorFor(model => model.MCombined_Sales.Customer_address, new { htmlAttributes = new { #class = "form-control", #Value = "N/A" } })
#Html.ValidationMessageFor(model => model.MCombined_Sales.Customer_address, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
#Html.LabelFor(model => model.MCombined_Sales.Payment_method, htmlAttributes: new { #class = "control-label " })
<div class="col-md-10">
#Html.EditorFor(model => model.MCombined_Sales.Payment_method, new { htmlAttributes = new { #class = "form-control", #Value = "Cash" } })
#Html.ValidationMessageFor(model => model.MCombined_Sales.Payment_method, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col">
<div class="form-group">
#Html.LabelFor(model => model.MCombined_Sales.Total_amout, htmlAttributes: new { #class = "control-label " })
<div class="col-md-10">
#Html.EditorFor(model => model.MCombined_Sales.Total_amout, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.MCombined_Sales.Total_amout, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
</div>
<div class="card-footer">
<table id="tblProduct" class="table" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>Order No</th>
<th>Product Name</th>
<th>Per Pice Price</th>
<th>Quantity</th>
<th>Amount</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" readonly value="" placeholder="Enter Order No " id="textBox_Order_No_cp" class="form-control" /></td>
<td><input type="text" value="1" placeholder="Search Product " id="textBox_Product_id" class="form-control" /></td>
<td><input type="number" value="15" min="0" placeholder="Enter Unit Price Product " id="textBox_Unit_price" class="form-control" /></td>
<td><input type="number" value="" step="1" min="1" placeholder="Enter Quantity" id="textBox_Quantity" class="form-control" /></td>
<td><input type="number" min="1" readonly value="" placeholder="Line Total" id="textBox_LineTotal" class="form-control" /></td>
<td><input type="button" id="btnAddProduct" value="Add" class="btn btn-sm" /></td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
#Html.EditorFor(model => model.MCombined_SalesDetail.Order_No_cp, new { htmlAttributes = new { #class = "form-control", #placeholder = "Order Number" } })
#Html.ValidationMessageFor(model => model.MCombined_SalesDetail.Order_No_cp, "", new { #class = "text-danger" })
</td>
<td>
#Html.EditorFor(model => model.MCombined_SalesDetail.Product_id, new { htmlAttributes = new { #class = "form-control", #placeholder = "ID" } })
#Html.ValidationMessageFor(model => model.MCombined_SalesDetail.Product_id, "", new { #class = "text-danger" })
</td>
<td>
#Html.EditorFor(model => model.MCombined_SalesDetail.Unit_price, new { htmlAttributes = new { #class = "form-control", #placeholder = "Unit Price", #min = "0" } })
#Html.ValidationMessageFor(model => model.MCombined_SalesDetail.Unit_price, "", new { #class = "text-danger" })
</td>
<td>
#Html.EditorFor(model => model.MCombined_SalesDetail.Quantity, new { htmlAttributes = new { #class = "form-control", #placeholder = "Quantity", #type = "number", #min = "1" } })
#Html.ValidationMessageFor(model => model.MCombined_SalesDetail.Quantity, "", new { #class = "text-danger" })
</td>
<td>
#Html.EditorFor(model => model.MCombined_SalesDetail.LineTotal, new { htmlAttributes = new { #class = "form-control", #placeholder = "LineTotal", } })
#Html.ValidationMessageFor(model => model.MCombined_SalesDetail.LineTotal, "", new { #class = "text-danger" })
</td>
<td></td>
</tr>
</tfoot>
</table>
</div>
<div id="btns">
<div class="form-group dataTables_wrapper">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn " id="AddClient" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="reset" value="Reset" class="btn" id="AddClient" />
</div>
</div>
<input type="submit" value="Testing Multi Row Table" class="btn btn-info close" id="btnTesting" />
</div>
</div> }
Use jQuery For Handle Multiple Models
$("#AddClient").click(function () {
var MCombined_Sales = {
Order_No: $('##Html.IdFor(model => model.MCombined_Sales.Order_No)').val(),
Customer_name: $('##Html.IdFor(model => model.MCombined_Sales.Customer_name)').val(),
Customer_phone: $('##Html.IdFor(model => model.MCombined_Sales.Customer_phone)').val(),
Customer_address: $('##Html.IdFor(model => model.MCombined_Sales.Customer_address)').val(),
Payment_method: $('##Html.IdFor(model => model.MCombined_Sales.Payment_method)').val(),
Total_amout: $('##Html.IdFor(model => model.MCombined_Sales.Total_amout)').val(),
Status_bit: $('##Html.IdFor(model => model.MCombined_Sales.Status_bit)').val(),
Created_by: $('##Html.IdFor(model => model.MCombined_Sales.Created_by)').val(),
Created_date: $('##Html.IdFor(model => model.MCombined_Sales.Created_date)').val(),
Modified_by: $('##Html.IdFor(model => model.MCombined_Sales.Modified_by)').val(),
Modified_date: $('##Html.IdFor(model => model.MCombined_Sales.Modified_date)').val()
};
var MCombined_SalesDetail = {
Order_No_cp: $('##Html.IdFor(model => model.MCombined_SalesDetail.Order_No_cp)').val(),
Product_id: $('##Html.IdFor(model => model.MCombined_SalesDetail.Product_id)').val(),
Unit_price: $('##Html.IdFor(model => model.MCombined_SalesDetail.Unit_price)').val(),
Quantity: $('##Html.IdFor(model => model.MCombined_SalesDetail.Quantity)').val(),
LineTotal: $('##Html.IdFor(model => model.MCombined_SalesDetail.LineTotal)').val()
};
var model = {
"MCombined_Sales": MCombined_Sales,
"MCombined_SalesDetail": MCombined_SalesDetail
}
$.ajax({
type: "POST",
url: "/Customer/Add",
data: model,
dataType: "json",
success: function (r) {
alert("id: " + r.Sale_id.toString());
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
I try use jQuery For Send Multiple Rows to db butt no success
$("body").on("click", "#btnAddProduct", function () {
//Reference the Name and Country TextBoxes.
var textBox_Order_No_cp = $("#textBox_Order_No_cp");
var textBox_Product_id = $("#textBox_Product_id");
var textBox_Unit_price = $("#textBox_Unit_price");
var textBox_Quantity = $("#textBox_Quantity");
var textBox_LineTotal = $("#textBox_LineTotal");
//Get the reference of the Table's TBODY element.
var tBody = $("#tblProduct > TBODY")[0];
//Add Row.
var row = tBody.insertRow(-1);
//Add textBox_Order_No_cp cells.
var cell = $(row.insertCell(-1));
cell.html(textBox_Order_No_cp.val());
//Add textBox_Product_id cell.
var cell = $(row.insertCell(-1));
cell.html(textBox_Product_id.val());
//Add textBox_Unit_price cell.
var cell = $(row.insertCell(-1));
cell.html(textBox_Unit_price.val());
//Add textBox_Quantity cell.
var cell = $(row.insertCell(-1));
cell.html(textBox_Quantity.val());
//Add textBox_LineTotal cell.
var cell = $(row.insertCell(-1));
cell.html(textBox_LineTotal.val());
//Add Button cell.
cell = $(row.insertCell(-1));
var btnRemove = $("<input />");
btnRemove.attr("type", "button");
btnRemove.attr("onclick", "Remove(this);");
btnRemove.addClass("btn btn-sm btn_row_remove")
btnRemove.val("x");
cell.append(btnRemove);
//Clear the TextBoxes.
//textBox_Order_No_cp.val("");
textBox_Product_id.val("");
textBox_Unit_price.val("");
textBox_Quantity.val("");
textBox_LineTotal.val("");
$('#btnAddProduct').attr("disabled", true);
});
function Remove(button) {
//Determine the reference of the Row using the Button.
var row = $(button).closest("TR");
var name = $("TD", row).eq(1).html();
//if (confirm("Do you want to delete: " + name)) {
// //Get the reference of the Table.
// var table = $("#tblProduct")[0];
// //Delete the Table row using it's Index.
// table.deleteRow(row[0].rowIndex);
//}
// if dirict delete with out msg
var table = $("#tblProduct")[0];
table.deleteRow(row[0].rowIndex);
};
$("body").on("click", "#btnTesting", function () {
//Loop through the Table rows and build a JSON array.
var DataMethod = new Array();
$("#tblProduct TBODY TR").each(function () {
var row = $(this);
var DataString = {};
DataString.MCombined_SalesDetail.Order_No_cp = row.find("TD").eq(0).html();
DataString.MCombined_SalesDetail.Product_id = row.find("TD").eq(1).html();
DataString.MCombined_SalesDetail.Unit_price = row.find("TD").eq(2).html();
DataString.MCombined_SalesDetail.Quantity = row.find("TD").eq(3).html();
DataString.MCombined_SalesDetail.LineTotal = row.find("TD").eq(4).html();
DataMethod.push(DataString);
alert("Check Array");
});
alert("Going To Ajax");
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Customer/Insert",
data: JSON.stringify(DataMethod),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
I have sent multiple models data to database successfully, but i face problems send multiple row data.

Have a null check on Model but still getting Null object reference ASP.NET MVC

controller
public ActionResult EditProduct(int id)
{
ProductViewModel ViewModel = new ProductViewModel();
ViewModel.SingleProduct = DB.Prouducts.Where(x => x.ProductID == id).FirstOrDefault();
ViewModel.ImageList = DB.ImageGalleries.Where(x => x.ProductIdFk == id).ToList();
return View(ViewModel);
}
[HttpPost]
public ActionResult EditProduct(Prouduct product, IEnumerable<HttpPostedFileBase> thumb, ImageGallery images)
{
CategoryDropdown();
BrandDropdown();
if (ModelState.IsValid)
{
HttpPostedFileBase Image1 = thumb.FirstOrDefault();
product.ProductSlug = slug;
var userID = Convert.ToInt32(Session["UserID"]);
product.UserIdFk = userID;
DB.Entry(product).State = System.Data.Entity.EntityState.Modified;
DB.SaveChanges();
int LastInsertedID = product.ProductID;
foreach (var tmb in thumb)
{
if (tmb != null)
{
string FileName = tmb.FileName;
string Extenstion = Path.GetExtension(FileName);
if (Extenstion.ToLower() == ".jpeg" | Extenstion.ToLower() == ".jpg" | Extenstion.ToLower() == ".png" | Extenstion.ToLower() == ".webp")
{
FileName = FileName + DateTime.Now.ToString("yyyyMMddHHmmssfff") + Extenstion;
string ImageSavePath = Server.MapPath("/Content/Assets/Photos/");
tmb.SaveAs(Path.Combine(ImageSavePath + FileName));
string ThumbSavePath = Server.MapPath("/Content/Assets/Photos/Thumbs/");
ThumbGenration.ResizeStream(522, tmb.InputStream, Path.Combine(ThumbSavePath + FileName));
images.ImageName = FileName;
images.ImageThumb = FileName;
images.ProductIdFk = LastInsertedID;
//var userID = Convert.ToInt32(Session["UserID"]);
images.UserIdFk = userID;
DB.ImageGalleries.Add(images);
DB.SaveChanges();
TempData["Success"] = "Data Added Successfully!";
}
}
}
}
return View();
}
View
#model RentalServices.Models.ProductViewModel
#using (Html.BeginForm("EditProduct", "Product", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.SingleProduct.ProductID);
<div class="add-item-wrapper">
<h4>Listing Details</h4>
<hr class="noPadMar" />
<div class="add-item">
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<div class="col-md-12 col-sm-12 form-group">
#*<label class="col-sm-3 col-md-3 control-label">Title</label>*#
#Html.LabelFor(model => model.SingleProduct.Title, htmlAttributes: new { #class = "col-sm-3 col-md-3 control-label" })
<div class="col-sm-9">
#*<input type="text" class="form-control" placeholder="TITLE" />*#
#Html.EditorFor(model => model.SingleProduct.Title, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SingleProduct.Title, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-12 col-sm-12 form-group">
#Html.LabelFor(model => model.SingleProduct.Price, htmlAttributes: new { #class = "col-sm-3 col-md-3 control-label" })
<div class="col-sm-9">
#Html.EditorFor(model => model.SingleProduct.Price, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SingleProduct.Price, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-12 col-sm-12 form-group">
#Html.Label("CATEGORY", htmlAttributes: new { #class = "col-sm-3 col-md-3 control-label" })
<div class="col-sm-9">
#Html.DropDownListFor(model => model.SingleProduct.CategoryIdFk, ViewBag.CategoryDropdown as SelectList, "CHOOSE CATEGORY", new { #class = "form-control", id = "CategoryID" })
#Html.ValidationMessageFor(model => model.SingleProduct.CategoryIdFk, "", new { #class = "text-danger" })
</div>
</div>
<div id="hide">
<div class="col-md-12 col-sm-12 form-group">
#Html.Label("BRAND", htmlAttributes: new { #class = "col-sm-3 col-md-3 control-label" })
<div class="col-sm-9">
#Html.DropDownListFor(model => model.SingleProduct.BrandIdFk, ViewBag.BrandDropdown as SelectList, "CHOOSE BRAND", new { #class = "form-control", id = "BrandID" })
#Html.ValidationMessageFor(model => model.SingleProduct.BrandIdFk, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-12 col-sm-12 form-group">
#Html.LabelFor(model => model.SingleProduct.Ram, htmlAttributes: new { #class = "col-sm-3 col-md-3 control-label" })
<div class="col-sm-9">
#Html.EditorFor(model => model.SingleProduct.Ram, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SingleProduct.Ram, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-12 col-sm-12 form-group">
#Html.LabelFor(model => model.SingleProduct.Processor, htmlAttributes: new { #class = "col-sm-3 col-md-3 control-label" })
<div class="col-sm-9">
#Html.EditorFor(model => model.SingleProduct.Processor, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SingleProduct.Processor, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-12 col-sm-12 form-group">
#Html.Label("CONDITION", htmlAttributes: new { #class = "col-sm-3 col-md-3 control-label" })
<div class="col-sm-9">
#Html.DropDownListFor(model => model.SingleProduct.Conditon, selectList, "CHOOSE CONDITION", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SingleProduct.Conditon, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-12 col-sm-12 form-group">
#Html.LabelFor(model => model.SingleProduct.Location, htmlAttributes: new { #class = "col-sm-3 col-md-3 control-label" })
<div class="col-sm-9">
#Html.EditorFor(model => model.SingleProduct.Location, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SingleProduct.Location, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-12 col-sm-12 form-group">
#Html.LabelFor(model => model.SingleProduct.Description, htmlAttributes: new { #class = "col-sm-3 col-md-3 control-label" })
<div class="col-sm-9">
#Html.TextAreaFor(model => model.SingleProduct.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SingleProduct.Description, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
</div>
</div>
<div class="image-gallery-wrapper">
<div class="img-gallery">
#if (Model.ImageList.Any())
{
foreach (var item in Model.ImageList)
{
<div class="img-wrapper">
<p>Image 1</p>
<div class="img-box">
<input type="file" name="thumb" value="" class="file-style" onchange="readURL(this)" ; />
<img src="/Content/Assets/Photos/Thumbs/#item.ImageName" alt="your image" id="imgName" value="#item.ImageName" />
<button id="RemoveImage">Remove Image</button>
</div>
</div>
}
}
</div>
</div>
<div class="text-center">
<button type="submit" class="roundSubmitBtn" style="background:#7048f0 !important;font-size:14px !important; margin-top:40px;">SUMBIT <i class="fa fa-arrow-right"></i></button>
</div>
}
As i added my code i am getting null exception error.but i have a check of null or not so why i am getting this null object reference error.
and i have also tried Count() and !=null in IF statement.i am getting erro while i submit form and error is null exception error so tell me where i am wrong
By inspecting POST action method provided in question, the problem seem coming from return View() statement which returns same view page as in GET action method but without returning viewmodel class instance, which causing ProductViewModel.ImageList contains null value.
The brief code below shows the problem:
[HttpPost]
public ActionResult EditProduct(Prouduct product, IEnumerable<HttpPostedFileBase> thumb, ImageGallery images)
{
CategoryDropdown();
BrandDropdown();
if (ModelState.IsValid)
{
// image processing and saving to DB
}
// the view returned without viewmodel
// this will trigger NullReferenceException because ProductViewModel.ImageList is not reassigned yet
return View();
}
Therefore, you should reassign ProductViewModel.ImageList property after saving posted data into database, and return the same view together with new ProductViewModel instance (or redirect to another action if necessary by following PRG pattern with RedirectToAction):
[HttpPost]
public ActionResult EditProduct(Prouduct product, IEnumerable<HttpPostedFileBase> thumb, ImageGallery images)
{
CategoryDropdown();
BrandDropdown();
if (ModelState.IsValid)
{
// image processing and saving to DB
}
// create viewmodel instance
var ViewModel = new ProductViewModel();
ViewModel.ImageList = ...; // reassign ImageList property here
return View(ViewModel);
}

How to resolve " System.ArgumentException: Value cannot be null or empty. Parameter name: contentPath" this error?

The following is my updateproduct.cshtml file where i am getting an error.
#model ShopperDB.Context.Product
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h2 class="admin-title text-center">Edit Product</h2>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ProductID)
<div class="form-group">
#Html.LabelFor(model => model.ProductName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.ProductName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ProductName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProductImage, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
<img src="#Url.Content(Model.ProductImage)" alt="IMAGES" height="300" ; width="300" />
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Price, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.Price, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Price, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CategoryID, "CategoryName", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.DropDownList("CategoryID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CategoryID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
</div>
</div>
</div>
</div>
}
The following is my update product method from product controller.
//Update the product
[HttpGet]
[Route("product/update/{id}")]
[CustomAuthorize("admin")]
public ActionResult UpdateTheProduct(int? id)
{
if (Session["UserName"].ToString() != null)
{
if (Session["UserName"].ToString() == "admin")
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
ViewBag.CategoryID = new SelectList(db.ProductCategories, "CategoryID", "CategoryName");
return View(product);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
return RedirectToAction("Index", "Home");
}
}
[HttpPost]
[ValidateAntiForgeryToken]
[Route("product/update/{id}")]
[CustomAuthorize("admin")]
public ActionResult UpdateTheProduct([Bind(Include = "ProductID,ProductName,ProductImage,Description,Price,CategoryID")] Product product)
{
if (ModelState.IsValid)
{
if (db.Products.Any(ac => ac.ProductName.Equals(product.ProductName)))
{
TempData["fail"] = "Category already Added";
}
else
{
TempData["notice"] = "Successfully Added";
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("ListOfProducts");
}
return View(product);
}
while i am updating the product it is showing me System.ArgumentException: Value cannot be null or empty.Parameter name: contentPath this error on storing ProductImage point.
So please kindly help me to resolve this error.
This part of code in your view potentially throwing contentPath exception:
<img src="#Url.Content(Model.ProductImage)" alt="IMAGES" height="300" ; width="300" />
If Model.ProductImage value is null or empty instead of containing a relative path string when passed to view, it will throw contentPath exception since Url.Content method cannot have null or empty argument.
To solve content URL issue, put if-condition check against null or empty value on ProductImage property in UpdateTheProduct (either GET or POST action method, or both of them) and set its default value using relative path:
if (String.IsNullOrEmpty(Model.ProductImage))
{
Model.ProductImage = "~/path/imagefile";
}
// some code
return View(product);
Related issues:
Value cannot be null or empty. Parameter name: contentPath
"Value cannot be null or empty. Parameter name: contentPath" on a most unexpected line on postback when ModelState has errors

defaulting value in MVC create view before http post

Hi I am trying to default a date with 'DateTime.Now' in a create view. And setting an 'Active' field to 'true'
The following code does that in the the following action in the controller:
// POST: RequestTypes/Create
// 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> Create([Bind(Include = "Id,RequestTypeDescription,LastUpdated,Active,Team")] RequestType requestType)
{
if (ModelState.IsValid)
{
db.RequestTypes.Add(requestType);
requestType.LastUpdated = System.DateTime.Now;
requestType.Active = true;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.Team = new SelectList(db.Teams, "Id", "TeamDescription", requestType.Team);
return View(requestType);
}
That is the httppost code which defaults when the save is made.
What I want to do is to default those fields so that they show when the create view first gets launched - with the following code in the following action:
// GET: RequestTypes/Create
public ActionResult Create()
{
ViewBag.Team = new SelectList(db.Teams, "Id", "TeamDescription");
ViewBag.LastUpdated = System.DateTime.Now;
return View();
}
My Create View code is the standard created by MVC scaffolding:
#model ManageHR5.Models.RequestType
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>RequestType</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.RequestTypeDescription, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RequestTypeDescription, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.RequestTypeDescription, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastUpdated, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastUpdated, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastUpdated, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Active, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Active)
#Html.ValidationMessageFor(model => model.Active, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Team, "Team", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Team", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Team, "", 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>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")}
When I run the app, and launch the create page, the defaults don't show up when the create page is launched.
What am I not understanding?
(A newbie to MVC :( )
You set them in the model on the Get for display purposes
// GET: RequestTypes/Create
public ActionResult Create() {
ViewBag.Team = new SelectList(db.Teams, "Id", "TeamDescription");
var model = new RequestType();
model.LastUpdated = System.DateTime.Now;
model.Active = true;
return View(model);
}
But like indicated in the provided comment
You set them immediately before you save the object in the POST method

How to decompress a varbinary file in database to a ZIP file?

In my application, I have to upload a ZIP file and then I have to make it available so that we can download that file again. As I am new to MVC, I have used a varbinary to store the data in the database.
Here is my view code:
#using (Html.BeginForm("Upload", "Createnews", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Createnew</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CategoryId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CategoryId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CategoryId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#*#using (Html.BeginForm("Upload", "Createnews", FormMethod.Post, new { enctype = "multipart/form-data" }))
{*#
<table>
<tr>
<td>File:</td>
<td>
<input type="file" name="UploadedFile" />
</td>
</tr>
<tr>
<td colspan="2">
#*<input type="submit" name="Upload" value="Submit" />*#
</td>
</tr>
</table>
#*}*#
#Html.LabelFor(model => model.Complete_ZIP_file, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Complete_ZIP_file, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Complete_ZIP_file, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CategoryName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CategoryName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CategoryName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SubCategoryId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SubCategoryId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SubCategoryId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SubCategoryName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SubCategoryName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SubCategoryName, "", 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" />*#<input type="submit" name="Upload" value="Submit" />
</div>
</div>
</div>
}
Then I have written the following code in the controller:
public ActionResult Upload([Bind(Include = "CategoryId,Complete_ZIP_file,CategoryName,SubCategoryId,SubCategoryName")] Createnew createnew)
{
if (Request != null)
{
HttpPostedFileBase file = Request.Files["UploadedFile"];
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
string fileName = file.FileName;
string fileContentType = file.ContentType;
byte[] fileBytes = new byte[file.ContentLength];
file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
createnew.Complete_ZIP_file = fileBytes;
}}
if (ModelState.IsValid)
{
db.Createnews.Add(createnew);
db.SaveChanges();
return RedirectToAction("Index");
}
//return View(createnew)
return View("Create");
}
Now, I the result is getting stored in the appropriate field. Now, I will have to make it available as a download. So, how can I convert this varbinary format to a ZIP file again?
Thanks in advance.
you dont need convert to varbinary to zip. you can directly write to response.
public ActionResult Download()
{
//read varbinary field from db
byte[] output = GetOutputFromDb();
return File(output, "application/zip", "fileName.zip");
}

Resources