I am working on update form, my scenario is I don't want to update new image I just want to update only other data then submit when I submit the form "image URL" shows the null value not show the old path of the image.i have tried this code which I am sharing you kindly tell me how to resolve this issue.
Just give the hint of code then I will resolve this.
Model
public class ProductViewModel{
public string ImageUrl { get; set; }
[NotMapped]
public HttpPostedFileBase imageUpload { get; set; }
public ProductViewModel()
{
ImageUrl = "~/Scripts/imageloading/image.jpg";
}
}
c#
public ActionResult AddOrEditProducts(ProductViewModel prod)
{
Product pro = new Product();
ProductDetail p_spec = new ProductDetail();
var result = new jsonMessage();
try
{
List<ProductType> PTlist = _IproductType.PTList();
ViewBag.Ptlist = new SelectList(PTlist, "PType_ID", "P_Name");
//Product Color List
List<P_Color> pColorList = _IProductColor.PColorlist();
ViewBag.pColor_List = new SelectList(pColorList, "C_ID", "C_Name_OR_Code");
List<P_Size> pSizeList = _ISize.pSizeList();
ViewBag.pSizeLists = new SelectList(pSizeList, "S_ID", "S_Size");
if (prod.imageUpload != null) // shows null here
{
string filename = Path.GetFileName(prod.imageUpload.FileName);
string _filename = DateTime.Now.ToString("yymmssff") + filename;
string extension = Path.GetExtension(prod.imageUpload.FileName);
prod.ImageUrl= "~/upload/" + _filename;
if (extension.ToLower() == ".jpeg" || extension.ToLower() == ".jpg" || extension.ToLower() == ".png")
{
if (prod.imageUpload.ContentLength <= 1000000)
{
prod.imageUpload.SaveAs(Path.Combine(Server.MapPath("~/upload/"), _filename));
p_spec = new ProductDetail();
p_spec.ProductID = prod.ProductID;
p_spec.OS = prod.OS.Trim();
p_spec.DualSim = prod.DualSim.Trim();
p_spec.Camera = prod.Camera.Trim();
p_spec.TouchScreen = prod.TouchScreen.Trim();
p_spec.ScreenSize = prod.ScreenSize.Trim();
p_spec.ProcessorType = prod.ProcessorType.Trim();
p_spec.RAM = prod.RAM.Trim();
p_spec.InternalMemory = prod.InternalMemory.Trim();
p_spec.Wifi = prod.Wifi.Trim();
p_spec.BatteryLife = prod.BatteryLife.Trim();
p_spec.Other = prod.Other.Trim();
p_spec.PDescription = prod.PDescription.Trim();
p_spec.Model = prod.Model.Trim();
p_spec.Condition = prod.Condition.Trim();
p_spec.Discount = prod.Discount;
p_spec.ImageUrl = prod.ImageUrl;
}
else
ViewBag.sizemsg = "Size Limit accessed ";
}
else
ViewBag.fileformat = "File is not Format is not Correct";
pro = new Product();
pro.ProductID = prod.ProductID;
pro.PName = prod.PName.Trim();
pro.ManificturedPrice = prod.ManificturedPrice;
pro.P_SizeID = prod.P_SizeID;
pro.P_Color_ID = prod.P_Color_ID;
pro.PType_ID = prod.PType_ID;
pro.UnitWeight = prod.UnitWeight;
pro.UnitInStock = prod.UnitInStock;
}
if (prod.ProductID == 0)
{
_IProducts.AddOrEditProducts(pro, p_spec);
result.Message= "Product has been saved success..";
result.Status = true;
ModelState.Clear();
}
else
{
_IProducts.AddOrEditProducts(pro, p_spec);
result.Message = "Product Update Successfully";
result.Status = true;
ModelState.Clear();
}
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
result.Message = "We are unable to process your request at this time. Please try again later.";
result.Status = false;
}
}
return RedirectToAction("ProductsList");
}
View
<div id="tabimage" class="tab-pane">
<h3 class="mgtp-15 mgbt-xs-20"> Images</h3>
<div class="vd_panel-menu">
<input type="submit" value="Save Changes" class="btn vd_btn vd_bg-blue btn-icon btn-sm save-btn fa fa-save" id="btnSave" />
<button type="reset" value="Cancel" class="btn vd_btn vd_bg-blue btn-icon btn-sm save-btn fa fa-save" id="" />
</div>
<div class="row">
<div class="form-group">
<label class="control-label col-lg-3 file_upload_label"> <span title="" data-toggle="tooltip" class="label-tooltip" data-original-title="Format JPG, GIF, PNG. Filesize 8.00 MB max."> Add a new image to this product </span> </label>
<div class="col-lg-9">
<div class="col-lg-5">
<span class="btn vd_btn vd_bg-green fileinput-button">
<i class="glyphicon glyphicon-plus"></i> <span>Add files...</span>
<input type="file" name="imageUpload" multiple id="imageUpload" onchange="ShowimahePreview(this,document.getElementById('previewImage'))" />
</span>
</div>
<div class="col-lg-4">
<img src="#Url.Content(Model.ImageUrl)" alt="Alternate Text" height="150" weight="" id="previewImage" />
</div>
</div>
</div>
</div>
</div>
Related
I'm using PagedList library for pagination and also have ordering and filtering. The problem is that after submit of order/filter request the pagination resets to page 1 but I have to keep it at current page? How can this be achieved? I also don't know if this is the right behavior but I was told to it is.
This is my controller:
public class ProductSearchBlockController : BlockController<ProductSearchBlock>
{
private readonly IRepository<Products> _productsRepository;
public ProductSearchBlockController(IRepository<Products> productsRepository)
{
_productsRepository = productsRepository;
}
public override ActionResult Index(ProductSearchBlock currentBlock)
{
if (Session[SessionConstants.Products] == null)
{
Session[SessionConstants.Products] = _productsRepository.All();
}
var sessionProducts = Session[SessionConstants.Products] as IEnumerable<Products>;
var searchString = Request.QueryString.Get(RequestQueryConstants.SearchString);
var orderBy = Request.QueryString.Get(RequestQueryConstants.OrderBy);
var pageNumber = Request.QueryString.Get(RequestQueryConstants.PageNumber);
if (string.IsNullOrEmpty(orderBy))
{
orderBy = "default";
}
if (!string.IsNullOrEmpty(searchString))
{
var result = sessionProducts.Where(p => p.OrganizaitonId.Contains(searchString) ||
p.ProductName.Contains(searchString)).ToList();
Session[SessionConstants.ProductsResult] = result;
}
else
{
var result = sessionProducts.ToList();
Session[SessionConstants.ProductsResult] = result;
}
var productsResult = Session[SessionConstants.ProductsResult] as List<Products>;
productsResult = TableDisplayHelper.OrderedProducts(orderBy, productsResult);
var viewModel = new ProductSearchBlockViewModel();
viewModel.Products = productsResult.ToPagedList(int.Parse(pageNumber), 2);
viewModel.PageNumber = int.Parse(pageNumber);
viewModel.OrderBy = orderBy;
viewModel.FilterBy = searchString;
viewModel.Options = currentBlock.Options;
return PartialView(viewModel);
}
public ActionResult GetTableData(string searchString, string orderBy, int? page)
{
if (searchString == null && orderBy == null)
{
return Redirect(PageHelper.CurrentPageUrl());
}
if (searchString != null)
{
page = 1;
}
int pageNumber = page ?? 1;
var orderByQuery = UriUtil.AddQueryString(PageHelper.CurrentPageUrl(), RequestQueryConstants.OrderBy, orderBy.ToString());
var SearchStringQuery = UriUtil.AddQueryString(orderByQuery, RequestQueryConstants.SearchString, searchString);
var finalUrl = UriUtil.AddQueryString(SearchStringQuery, RequestQueryConstants.PageNumber, pageNumber.ToString());
return Redirect(finalUrl);
}
This is the view:
<div class="block esproductsearchblock col-lg-12 col-md-12 col-sm-12 col-xs-12 ">
<div class="es-product-search-block es-product-search-block-index b-spacing-default fonts-regular template-base block-wrapper">
<div class="template-search-block wrapper-fullsize" data-is-pagination-enabled="True" style="opacity: 1; pointer-events: auto;">
<section class="product-search wrapper-940" style="opacity: 1; pointer-events: auto;">
#using (Html.BeginForm("GetTableData", "ProductSearchBlock", FormMethod.Get))
{
<span>Order By</span>
<select id="orderBySelect" name="orderBy" aria-hidden="true">
#if (Model.Options != null)
{
foreach (var item in Model.Options)
{
if (Model.OrderBy == item.Trim().ToLower())
{
<option value="#item" selected>#item</option>
}
else
{
<option value="#item">#item</option>
}
}
}
</select>
<div class="search-field bottom-aligned-m">
<input id="search-field-inputid" class="search-field-input" name="searchString" placeholder="Search" value="#Model.FilterBy">
<i class="fa fa-close"></i>
</div>
<button class="btn">Submit Search</button>
<a class="btn" href="/ProductSearchBlock/GetTableData">Clear Search</a>
<div id="distribution-status-filter" data-distribution-status-filter-id="251" data-distributon-status-options="Phased out,Mature,Active"></div>
}
</section>
<div class="search-results-table wrapper-940">
<section class="results">
<div class="products">
#foreach (var product in Model.Products)
{
<div class="product product-data">
<div class="title-container">
<p class="product-name">#product.ProductName</p>
</div>
<div class="group">
<p class="indication">#product.OrganizaitonId</p>
</div>
<div class="price">
<h6>Price per Unit</h6>
<p class="small-text bold">
#product.Price <span class="product-price__currency-marker">€</span>
</p>
</div>
#using (Html.BeginForm("AddToCart", "ProductSearchBlock", FormMethod.Get))
{
<div class="float-container">
<div class="float-child">
<h6>Quantity</h6>
<input min="1" style="width:50%" type="number" name="quantity" value="0">
<input hidden type="number" name="id" value="#product.Id">
</div>
<div class="float-child">
<button class="cart-btn primary-btn">Add</button>
</div>
</div>
}
</div>}
</div>
#Html.PagedListPager(Model.Products, page => Url.Action("GetTableData", "ProductSearchBlock",
new
{
page,
orderBy = Model.OrderBy,
searchString = Model.FilterBy
}),
new PagedListRenderOptions
{
ContainerDivClasses = new List<string> { "pagination" }, LiElementClasses = new List<string> { "paginationSpan" }
});
</section>
</div>
</div>
</div>
Found a solution maybe there is a better version but current one works.
Added parameter pageNumber to form and changed form to post:
#using (Html.BeginForm("GetTableData", "ProductSearchBlock", new { pageNumber=Model.PageNumber}, FormMethod.Post))
In controller get the current page number and check if exists set page to current page
public ActionResult GetTableData(string searchString, string orderBy, int? page)
{
var currentPage = Request.QueryString.Get(RequestQueryConstants.PageNumber);
if (searchString == null && orderBy == null)
{
return Redirect(PageHelper.CurrentPageUrl());
}
if(currentPage != null)
{
page = int.Parse(currentPage);
}
var orderByQuery = UriUtil.AddQueryString(PageHelper.CurrentPageUrl(), RequestQueryConstants.OrderBy, orderBy.ToString());
var SearchStringQuery = UriUtil.AddQueryString(orderByQuery, RequestQueryConstants.SearchString, searchString);
var finalUrl = UriUtil.AddQueryString(SearchStringQuery, RequestQueryConstants.PageNumber, page.ToString());
return Redirect(finalUrl);
}
I am trying to use Action-[HttpPost] in my ASP MVC project however the Post Action doesn't seems to work.After Submit button Page will showing Error.
Following is my model:
public class bcSlider
{
public int sliderID { get; set; }
public string sliderImage { get; set; }
}
Following is my ManageOperations:
public class MngSlider
{
public int insertSlider(bcSlider obj)
{
int condition = 0;
try
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ospDB"].ConnectionString);
SqlCommand cmd = new SqlCommand("usp_InsertConfrence", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#SliderImage", obj.ImageName);
if (con.State.Equals(ConnectionState.Closed))
con.Open();
condition = cmd.ExecuteNonQuery();
con.Close();
if (condition > 0)
{
return 1;
}
else
{
return 0;
}
}
catch (Exception ex)
{
throw ex;
}
}
}
Following is Controller:
public class AdminSliderController : Controller
{
bcSlider modelSlider = new bcSlider();
MngSlider objSlider = new MngSlider();
//---------------INSERT---------------//
// GET: /AdminSlider/AddSlider
public ActionResult AddSlider()
{
bcSlider mSlider = new bcSlider();
return View(mSlider);
}
// POST: /AdminSlider/AddSlider
[HttpPost]
public ActionResult AddSlider(HttpPostedFile file, bcSlider mSlider)
{
if (ModelState.IsValid)
{
//File Available Verification
if (file != null && file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName); //FileName
string fileExtension = Path.GetExtension(fileName); //FileExtension
//Extension Verification
if (fileExtension.ToLower() == ".jpg" || fileExtension.ToLower() == ".jpeg" || fileExtension.ToLower() == ".png" || fileExtension.ToLower() == ".pdf" || fileExtension.ToUpper() == ".JPG" || fileExtension.ToUpper() == ".JEPG" || fileExtension.ToUpper() == ".PNG" || fileExtension.ToUpper() == ".PDF")
{
//FileSize Verification
int length = file.ContentLength;
if (length <= 1000)
{
string filepath = Path.Combine(Server.MapPath("~/ImagesDirectory/"), fileName); //FilePath
file.SaveAs(filepath);
objSlider.insertSlider(mSlider); //Insert to DB
ViewBag.Message = "<script>alert('File Inserted Successfully !')</script>";
ModelState.Clear();
}
else
{
ViewBag.SizeMessage = "<script>alert('Size Should be of 1MB !')</script>";
}
}
else
{
ViewBag.ExtensionMessage = "<script>alert('File Not Supported !')</script>";
}
}
else
{
ViewBag.Message = "<script>alert('Invalid File !')</script>";
}
}
else
{
ViewData["result"] = "Registration Not Successful";
}
return RedirectToAction("AddSlider");
}
}
}
Following is htmlcs:
#model OspWebsite.Models.bcSlider
#{
ViewBag.Title = "AddSlider";
Layout = "~/Views/Shared/LayoutAdmin.cshtml";
}
<div class="content-header">
<!-- Page Name -->
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1 class="m-0 text-dark">Slider</h1>
</div><!-- /.col -->
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item">Home</li>
<li class="breadcrumb-item active">Slider</li>
</ol>
</div><!-- /.col -->
</div><!-- /.row -->
</div>
#Html.Raw(ViewBag.Message)
#Html.Raw(ViewBag.SizeMessage)
#Html.Raw(ViewBag.ExtensionMessage)
#using (Html.BeginForm("AddSlider", "AdminSlider", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<!-- Input Forms -->
<div class="row">
<div class="offset-md-1 mt-5 col-md-10">
<div class="card card-success">
<div class="card-header">
<h3 class="card-title">Add New Slider</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-widget="maximize"><i class="fas fa-expand"></i></button>
<button type="button" class="btn btn-tool" data-widget="collapse"><i class="fas fa-minus"></i></button>
</div>
<!-- /.card-tools -->
</div>
<!-- /.card-header -->
<div class="card-body">
<div class="card-body">
<div class="form-group">
<div class="col-sm-12 ">
<label for="inputEmail3" class="col-sm-4 control-label">Select Slider</label>
<div class="custom-file">
<label class="custom-file-label" for="exampleInputFile"></label>
<input type="file" name="sliderImage" value=#Model.sliderImage class="custom-file-input" id="exampleInputFile">
</div>
</div>
</div>
</div>
<!-- /.card-body -->
</div><div class="card-footer">
<button type="submit" class="btn btn-success">Upload</button>
<button type="submit" class="btn btn-default float-right">Cancel</button>
</div>
<!-- /.card-footer -->
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
<!-- /.col -->
</div>
}
</div>
The GET Action is Calling But POST Action is Showing Error.
i am inserting Image in Database.
You are having the error because of the parameter you are passing in the controller HttpPostedFile
HttpPostedFileBase and HttpPostedFile
are definitely not the same.
Change your method to
[HttpPost]
public ActionResult AddSlider(HttpPostedFileBase sliderImage, bcSlider mSlider)
{
//your code here.
}
Notice that I used sliderImage because that was also what you have in your form.
Again Your form, which I don't know if it was a typo error is setting the value of a file-input
<input type="file" name="sliderImage" value=#Model.sliderImage class="custom-file-input" id="exampleInputFile">
You are not supposed to do that.
Again and on lighter note, if it is also not a typo, you don't have any attribute in you class obj.ImageName but you have the below in your insertSlider method
cmd.Parameters.AddWithValue("#SliderImage", obj.ImageName);
For more on HttpPostedFileBase and HttpPostedFile and see here
That's all for now.
Edit: I got how to refresh the page on success, but it just creates 2 calls to my controller method, which is unnecessary and the page doesn't update on 1st call. Can anyone help to update the page on first call?
Now I am new to Ajax calls so, I don't know how to refresh my view Or Webgrid after executing my controller method.
And I am also unable to find whether success method is called or not in Ajax.
And I am facing this in every Ajax call, why View isn't updated when returned by controller method.
What I have done is, there is a DropDownlist,and on selecting a value and submitting displays a webgrid.
Webgrid has checkboxes and on selecting checkboxes and clicking on submit passes some data through AJax to controller method. The Data gets updated in DataBase but it is not reflected in view Until I refresh it.
How to refresh View automatically?
Any help would be appreciated.
I have a View as follows:
$("#save_btn").on("click", function () {
var ischecked = 0;`enter code here`
$('#tblFormentry').find("input:checkbox").each(function () {
if (this.checked) {
var chck = $(this).attr("value");
var hidden = $(this).closest('td').find(':hidden');
villcode = villcode + "," + hidden.val();
singlestring = singlestring + "," + chck;
}
});
if ((singlestring != null && singlestring != "") && (villcode != null && villcode != "")) {
alert(singlestring);
if (confirm("Are you sure?") == true) {
$.ajax({
url: "#Url.Action("getmultipleids", "Admin")",
contentType: "application/json; charset=utf-8",
data: { 'ids': singlestring, 'villcode': villcode },
type: "GET",
cache: false,
success: function (result) {
$("body").html(result);
singlestring = "";
villcode = "";
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
else {
singlestring = "";
}
}
else {
alert("Please select at least 1 Entry!");
}
});
<div class=" col-md-10">
#using (Html.BeginForm("GetGridData", "Admin", FormMethod.Post, new { #id = "verifyentry_form", role = "form" }))
{
#*#Html.ValidationSummary(false, "", new { #class = "text-danger" })*#
if (!string.IsNullOrEmpty(Convert.ToString(TempData["ErrorMessage"])))
{
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Error! </strong>#TempData["ErrorMessage"].ToString()
<div style="display:none">#TempData.Remove("ErrorMessage")</div>
</div>
}
if (!string.IsNullOrEmpty(Convert.ToString(TempData["Message"])))
{
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong></strong>#TempData["Message"].ToString()
<div style="display:none">
#TempData.Remove("Message")
</div>
</div>
}
<div class="panel-default box box-primary">
<div class="panel-heading">
<h2 class="panel-title">Verify Entry</h2>
</div>
<div class="panel-body">
<div class="row">
<div class="form-group">
#Html.LabelFor(model => model.agency_id, new { #class = "control-label" })
#*#Html.DropDownListFor(m => m.DistID, (SelectList)TempData["Districts"], "Select", new { #class = "form-control" })*#
#Html.DropDownListFor(model => model.agency_id, (SelectList)#ViewBag.Agencylist, "Select", new { #class = "form-control", #id = "ddID" })
</div>
</div>
<div class=" row ">
<input type="button" name="submitbtn" value="Submit" class="btn btn-primary" id="databtn" />
</div>
</div>
</div>
}
<div class="box box-primary" id="ajaxdiv">
#if (ViewBag.formentry != null)
{
int PageSizeValue = 1;
//if (!string.IsNullOrEmpty(Convert.ToString(Session["Tbl_TraMstPageSizeValue"])))
//{
// PageSizeValue = Convert.ToInt32(Session["Tbl_TraMstPageSizeValue"]) > 0 ? Convert.ToInt32(Session["Tbl_TraMstPageSizeValue"]) : 1;
//}
WebGrid grid = new WebGrid(ViewBag.formentry, ajaxUpdateContainerId: "ajaxdiv", rowsPerPage: 10, ajaxUpdateCallback: "DetailsUpdate");
#grid.GetHtml(
htmlAttributes: new { id = "tblFormentry" },
tableStyle: " table table-bordered table-hover dataTable", headerStyle: "",
mode: WebGridPagerModes.All,
firstText: "<<",
lastText: ">>",
nextText: ">",
previousText: "<",
columns: new[]{
#*grid.Column(header:"{checkall}",format:#<text>
<input type="checkbox" name="Tbl_TraMstId" value="#item.agency_id" onclick="CheckClick(this)" />
</text>,style:"TableCheckBoxStyle",canSort:false),*#
grid.Column("district_name","District Name",canSort:false),
grid.Column("block_name","Block Name",canSort:false),
grid.Column("village_name","Village Name", canSort:false),
grid.Column("name","Name", canSort:false),
grid.Column("formno","Form No", canSort:false),
grid.Column("agency_name","Agency Name", canSort:false),
//grid.Column("Verify", format: (item) => item.GetSelectLink(item.formno)),
grid.Column("Verify",format:#<text>
<form method="post" action="" id="chckboxform">
<input type="hidden" name="village_code" value="#item.village_code" />
<input type="checkbox" name="formno" value="#item.formno" id="chckbox1" />
</form>
</text>,style:"tablebutton",canSort:false)
})
}
</div>
<input type="button" name="submit" value="Submit" id="save_btn" class="btn btn-primary" />
<input type="button" name="reset" value="Reset" id="reset_btn" class="btn btn-primary" />
Following is the controller method that is being called with the help of jQuery AJax call.
public ActionResult getmultipleids(string ids, string villcode)
{
//need verificatN date, verified, verification user = admin, formno, villagecode
int i;
string[] formno = ids.Split(',');
string[] village_code = villcode.Split(',');
DataTable dt = new System.Data.DataTable("Entries");
DateTime today = DateTime.Today;
DataRow dr;
DataColumn dc;
dt.Columns.AddRange(new DataColumn[5] {
new DataColumn("verification_date", typeof(DateTime)),
new DataColumn("verified", typeof(Char)),
new DataColumn("verification_user", typeof(string)),
new DataColumn("formno", typeof(Int64)),
new DataColumn("village_code", typeof(string))
});
for (i = 1; i < formno.Count(); i++)
{
dr = dt.NewRow();
dr["verification_date"] = today;
dr["verified"] = 'Y';
dr["verification_user"] = "admin";
dr["formno"] = Int64.Parse(formno[i]);
dr["village_code"] = village_code[i];
dt.Rows.Add(dr);
}
try
{
actionResult = objfamilyBAL.Update_Entry(dt);
TempData["Message"] = actionResult.Message;
ViewBag.Agencylist = (SelectList)Session["ddlist"];
if (ShowResultMessage(actionResult, true, false))
{
int op = 1;
int agncyid = (int)Session["agency_id"];
String WorkArea = Session["wrkArea"].ToString();
actionResult = objfamilyBAL.Fetch_verify_griddata(op, agncyid, WorkArea);
if (actionResult.IsResult)
{
List<CommonTableEntity> family_entitylist = (List<CommonTableEntity>)actionResult.ObjResult;
ViewBag.formentry = family_entitylist;
}
}
if (actionResult.IsErrorMessage)
{
TempData["ErrorMessage"] = actionResult.ErrMessage;
}
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
return View("VerifyEntry");
}
Sorry for long post.
I am new to asp.net core. I am facing a problem when uploading a file(image) with my model.
the viewmodel :
namespace WebApplication1.ViewModels
{
public class HotelViewModel
{
public String NomHotel { get; set; }
public String NomAgence { get; set; }
public String Filepath{ get; set; }
}
}
this is the cshtml :
#model WebApplication1.ViewModels.HotelViewModel
<form novalidate method="post" enctype="multipart/form-data" asp-
controller="Hotel" asp-action="Hotel">
<div id="parent">
<div id="wide" class="col-lg-4">
<div asp-validation-summary="ModelOnly"></div>
<div class="form-group">
<label asp-for="NomHotel"></label>
<input asp-for="NomHotel" class="form-control" />
<span asp-validation-for="NomHotel"></span>
</div>
<div class="form-group">
<label asp-for="NomAgence"></label>
<input asp-for="NomAgence" class="form-control" />
<span asp-validation-for="NomAgence"></span>
</div>
<div class="col-md-10">
<p>Upload one or more files using this form:</p>
<input type="file" name="files" multiple class="btn" />
</div>
<div id="#rest">
<div class="form-group">
<input type="submit" value="Ajouter" class="btn btn-lg btn-
success ahbat" />
</div>
</div>
</div>
</div>
and this is the controller :
[HttpPost]
public IActionResult Hotel(HotelViewModel mod)
{
Hotel hotel = new Hotel
{
NomAgence = mod.NomAgence,
NomHotel = mod.NomHotel
};
var newFileName = string.Empty;
if (HttpContext.Request.Form.Files != null)
{
var fileName = string.Empty;
string PathDB = string.Empty;
var files = HttpContext.Request.Form.Files;
foreach (var file in files)
{
if (file.Length > 0)
{
//Getting FileName
fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
//Assigning Unique Filename (Guid)
var myUniqueFileName = Convert.ToString(Guid.NewGuid());
//Getting file Extension
var FileExtension = Path.GetExtension(fileName);
// concating FileName + FileExtension
newFileName = myUniqueFileName + FileExtension;
// Combines two strings into a path.
fileName = Path.Combine(_environment.WebRootPath, "HotelImg") + $#"\{newFileName}";
// if you want to store path of folder in database
PathDB = "demoImages/" + newFileName;
hotel.Piscine = newFileName;
using (FileStream fs = System.IO.File.Create(fileName))
{
file.CopyTo(fs);
fs.Flush();
}
}
}
}
IH.Create(hotel);
return View();
}
as said I have tried different combinations of code but I always get the file or the model never both and I need both of them. This is the most correct code I can show you sorry if it is not too clear.
When I am using this code as web view, it works fine, but when with developer option in Chrome I select Mobile View, FormCollection shows empty strings in the controller
VIEW (Edit updtaed)
<div class="page product-details-page deal-product-details-page">
#using (Html.BeginForm("AddProductToCart_Details", "DealProduct", new { productId = Model.Id, shoppingCartTypeId = 1 }, FormMethod.Post))
{
<div class="page-body">
#using (Html.BeginRouteForm("Product", new { SeName = Model.SeName }, FormMethod.Post, new { id = "product-details-form" }))
{
#{
var dataDictAttributes = new ViewDataDictionary();
dataDictAttributes.TemplateInfo.HtmlFieldPrefix = string.Format("attributes_{0}", Model.Id);
#Html.Partial("~/Views/Product/_ProductAttributes.cshtml", Model.ProductAttributes, dataDictAttributes)
}
<!--gift card-->
#{
var dataDictGiftCard = new ViewDataDictionary();
dataDictGiftCard.TemplateInfo.HtmlFieldPrefix = string.Format("giftcard_{0}", Model.Id);
#Html.Partial("~/Views/Product/_GiftCardInfo.cshtml", Model.GiftCard, dataDictGiftCard)
}
<!--rental info-->
#{
var dataDictRental = new ViewDataDictionary();
dataDictRental.TemplateInfo.HtmlFieldPrefix = string.Format("rental_{0}", Model.Id);
#Html.Partial("~/Views/Product/_RentalInfo.cshtml", Model, dataDictRental)
}
<!--price & add to cart-->
#{
var dataDictPrice = new ViewDataDictionary();
dataDictPrice.TemplateInfo.HtmlFieldPrefix = string.Format("price_{0}", Model.Id);
#Html.Partial("~/Views/Product/_ProductPrice.cshtml", Model.ProductPrice, dataDictPrice)
#Html.Partial("~/Views/Product/_ProductTierPrices.cshtml", Model.TierPrices)
}
<!--wishlist, compare, email a friend-->
<!--attributes-->
#{
var item = #Model.AssociateProductAttributesList.Where(x => x.Item1 == data.Id).Select(x => x.Item2).ToList()[0];
bool isAttributes =false;
}
<div class="popup" data-popup="popup-#data.Id">
<div class="popup-inner">
<h2>#data.Name</h2>
<p>#data.ShortDescription</p>
<br />
#foreach (System.Collections.DictionaryEntry value in item)
{
var val = data.Id + "_" + value.Key.ToString();
isAttributes = true;
#*<div class="attributes">*#
<dl>
<dt id="product_attribute_label_19">
<label class="text-prompt">
#value.Key.ToString()
</label>
</dt>
<dd id="product_attribute_input_19" class="product_attribute_inputdiv_#val">
#Html.DropDownList("Attributes," + data.Id + "," + value.Key.ToString(), new SelectList((System.Collections.IEnumerable)value.Value, "Id", "Name"), "--- Please select ---")
</dd>
</dl>
#*</div>*#
}
<br />
<div onclick="ImageBlur('div_#data.Id')" class="buttons" style="text-align:left;">
<input class="button-1" data-popup-close="popup-#data.Id" type="button" value="Add to back" />
</div>
<a class="popup-close" data-popup-close="popup-#data.Id" href="#">x</a>
</div>
</div>
#if (item.Count == 0)
{
#Html.Hidden("Attributes," + data.Id + ",", "0")
<div class="popup" data-popup="popup-#data.Id">
<div class="popup-inner">
<h2>#data.Name</h2>
<p>#data.ShortDescription</p>
<div onclick="ImageBlur('div_#data.Id')" class="buttons" style="text-align:left;">
<input class="button-1" data-popup-close="popup-#data.Id" type="button" value="Add to back" />
</div>
<a class="popup-close" data-popup-close="popup-#data.Id" href="#">x</a>
</div>
</div>
}
#if (isAttributes)
{
<a style="color: blue;" data-popup-open="popup-#data.Id" href="#">
<img id="imgdiv_#data.Id" src="~/Themes/Playground/Content/img/dealselectattribut.png" class="select-atr-img" style="width: 50%; margin-bottom: 10px;"/>
</a>
}
</div>
}
</div>
<div>
</div>
#{
var dataDictAddToCart = new ViewDataDictionary();
dataDictAddToCart.TemplateInfo.HtmlFieldPrefix = string.Format("addtocart_{0}", Model.Id);
<div class="overview" style="width:100%; margin-left:auto">
#Html.Partial("~/Views/Product/_AddToCart.cshtml", Model.AddToCart, dataDictAddToCart)
</div>
}
</div>
}
</div>
}
</div>
Controller
public ActionResult AddProductToCart_Details(int productId, int shoppingCartTypeId, FormCollection form)
{
if (_productService.IsDealProducts(productId))
{
if (!IsCompleteSelected(form))
{
return Json(new
{
success = false,
message = " Plese select all associated product attribute "
});
}
}
//more code here
}
Normal View (Web View)
Mobile View
Form in form is not allowed. This is your issue.