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.
Related
I'm migrating my ASP .NET MVC app from .NET Framework 4.8 to .NET 6 and have encountered problem that Html.RenderAction method from System.Web.Mvc.Html namespace no longer works and I'm getting an error in my code:
if (Model.IsCrawler)
{
Html.RenderAction("GetLanguageSelector", "languageSelectorAsync", new { brand = Model.Layout.BrandShortName, cultureInfo = Model.CurrentPage.CurrentLanguage });
}
This method is accessing LanguageSelectorAsyncController:
public class LanguageSelectorAsyncController : Microsoft.AspNetCore.Mvc.Controller
{
private readonly IContentLoader contentLoader;
private readonly IContentLanguageAccessor contentLanguageAccessor;
public LanguageSelectorAsyncController(
IContentLoader contentLoader, IContentLanguageAccessor contentLanguageAccessor)
{
this.contentLoader = contentLoader;
this.contentLanguageAccessor = contentLanguageAccessor;
}
public Microsoft.AspNetCore.Mvc.ActionResult GetLanguageSelector(string brand, CultureInfo cultureInfo)
{
contentLanguageAccessor.Language = cultureInfo;
HomePage homePage = ContentReference.StartPage.Get<HomePage>();
if (homePage?.SiteSettingsLink != null)
{
SiteSettings settingsPage = contentLoader.Get<SiteSettings>(homePage.SiteSettingsLink, cultureInfo) ?? contentLoader.Get<SiteSettings>(homePage.SiteSettingsLink);
if (settingsPage != null)
{
if (brand == "rockstar")
{
return PartialView("Content/BrandSelectorBlock", settingsPage.RockstarLanguageSelector);
}
else if (brand == "green")
{
return PartialView("Content/BrandSelectorBlock", settingsPage.GreenLanguageSelector);
}
else if (brand == "rockfon")
{
return PartialView("Content/BrandSelectorBlock", settingsPage.RockfonLanguageSelector);
}
else if (brand == "rockpanel")
{
return PartialView("Content/BrandSelectorBlock", settingsPage.RockpanelLanguageSelector);
}
else if (brand == "lapinus")
{
return PartialView("Content/BrandSelectorBlock", settingsPage.LapinusLanguageSelector);
}
else if (brand == "language")
{
return PartialView("Content/LanguageSelectorBlock", settingsPage.LanguageSelector);
}
}
}
return null;
}
}
...which in turn uses views BrandSelectorBlock:
#model BrandSelectorBlock
#{
var list = Model.Continents;
var tabs = list.Item1;
var tabCount = "has-" + tabs.Count() + "-tabs";
var NoEurope = string.IsNullOrWhiteSpace(tabs.Where(x => x.Equals(Continents.Europe)).FirstOrDefault());
TempData.AddStyles(OrganismStyle.O23Tabs);
TempData.AddOrganismScripts(ViewScript.O23TabsView);
}
<header class="modal-multi-selector__header">
<div class="container">
<button type="button" class="modal-multi-selector__close js-lang__close"></button>
#if (!string.IsNullOrWhiteSpace(Model.BrandLogo))
{
<figure class="modal-multi-selector__logo">
#SvgHelper.GetSVG(Model.BrandLogo)
</figure>
}
<div class="modal-multi-selector__description">
<p class="body-text-2">#Html.ExtendedPropertyFor(x => x.BodyText)</p>
<p class="body-text-2 is-hidden">#Html.ExtendedPropertyFor(x => x.VisitorMessage)</p>
</div>
<h3 class="modal-multi-selector__title">#Html.ExtendedPropertyFor(x => x.Heading)</h3>
</div>
<div class="O23-tabs #tabCount is-filter">
<nav class="O23-tabs__nav">
<div class="container">
<ul class="O23-tabs__list is-hidden-sm">
#for (var i = 0; i < tabs.Count(); i++)
{
var tab = tabs.ElementAt(i);
var isActive = "";
if (tab.ToLower().Equals(Continents.Europe.ToLower()) || (NoEurope && i == 0))
{
isActive = "is-active";
}
<li class="O23-tabs__item #isActive">
<span>#tab</span>
</li>
}
<li class="O23-tabs__list__indicator"></li>
</ul>
<div class="O23-tabs__select is-hidden-md">
<div class="select">
<div class="select__wrap">
<div class="select__wrap__elem">
<select class="select__elem js-select" name="countries">
#for (var i = 0; i < tabs.Count(); i++)
{
var tab = tabs.ElementAt(i);
var selected = "";
if (tab.Equals(Continents.Europe) || (NoEurope && i == 0))
{
selected = "selected";
}
<option #selected value="#tab.ToLower()">#tab</option>
}
</select>
</div>
#SvgHelper.GetSVG("small-arrow-down")
</div>
</div>
</div>
</div>
</nav>
</div>
</header>
<div class="modal-multi-selector__content">
<div class="modal-multi-selector__content__inner">
<div class="container">
<ul class="modal-multi-selector__list">
#foreach (var langItem in list.Item2)
{
<li class="modal-multi-selector__item" data-country-code="#langItem.CountryCode.ToLower()" data-filter="#langItem.Continent.ToLower()">#langItem.DisplayString</li>
}
</ul>
</div>
</div>
</div>
And LanguageSelectorBlock:
#model LanguageSelectorBlock
#{
var list = Model.Continents;
var tabs = list.Item1;
var tabCount = "has-" + tabs.Count() + "-tabs";
TempData.AddOrganismScripts(ViewScript.O23TabsView);
}
<header class="modal-multi-selector__header">
<div class="container">
<button type="button" class="modal-multi-selector__close js-lang__close"></button>
#if (!string.IsNullOrWhiteSpace(Model.BrandLogo))
{
<figure class="modal-multi-selector__logo">
#SvgHelper.GetSVG(Model.BrandLogo)
</figure>
}
<h3 class="modal-multi-selector__title">#Model.Heading</h3>
</div>
<div class="O23-tabs #tabCount is-filter">
<nav class="O23-tabs__nav">
<div class="container">
<ul class="O23-tabs__list is-hidden-sm">
#for (var i = 0; i < tabs.Count(); i++)
{
var tab = tabs.ElementAt(i);
var isActive = "";
if (i == 0)
{
isActive = "is-active";
}
<li class="O23-tabs__item #isActive">
<span>#tab</span>
</li>
}
<li class="O23-tabs__list__indicator"></li>
</ul>
<div class="O23-tabs__select is-hidden-md">
<div class="select">
<div class="select__wrap">
<div class="select__wrap__elem">
<select class="select__elem js-select" name="countries">
#for (var i = 0; i < tabs.Count(); i++)
{
var tab = tabs.ElementAt(i);
var selected = "";
if (i == 0)
{
selected = "selected";
}
<option #selected value="#tab.ToLower()">#tab</option>
}
</select>
</div>
#SvgHelper.GetSVG("small-arrow-down")
</div>
</div>
</div>
</div>
</nav>
</div>
</header>
<div class="modal-multi-selector__content">
<div class="modal-multi-selector__content__inner">
<div class="container">
<ul class="modal-multi-selector__list">
#foreach (var langItem in list.Item2)
{
var active = langItem.CountryCode.Equals(ContentLanguage.PreferredCulture.Name, StringComparison.OrdinalIgnoreCase)
? "is-active" : "";
<li class="modal-multi-selector__item #active" data-filter="#langItem.Continent.ToLower()">#langItem.DisplayString</li>
}
</ul>
<div class="modal-multi-selector__more">
#Html.ExtendedPropertyFor(x => x.MoreInfoButton)
</div>
</div>
</div>
</div>
I have tried using Html.PartialAsync and Html.RenderPartialAsync methods, but they aren't quite like for like replacement for Html.RenderAction and so did not work. I have also read about ViewComponents, but I don't know how to implement them in my code.
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 working on load more data functionality as per my requirement I am displaying 12 records for the first time and it works fine for me but whenever I am trying to show the rest data the earlier data is getting lost and the current data is displaying.
For this purpose, I am using a list which is coming from code behind but my problem is I'd declared the List on the view which is initialized each and every time then every time it becomes null on at the time of data binding that is the reason earlier data is getting lost.
For this purpose, I can not use AJAX
Here is my View
#model List<ChangiRecommends.BAL.ViewModel.Product.ProductViewModel>
#using ChangiRecommends.BAL.ViewModel.Product;
#using ChangiRecommends.Utilities;
#{
if(ViewBag.productCount > 12)
{
}
List<ProductViewModel> productList = new List<ProductViewModel>();
if(productList.Count == 0)
{
productList = Model;
}
else
{
productList.AddRange(Model);
}
ViewBag.Title = "destination";
Layout = "~/Views/Shared/_Layout.cshtml";
var key = ViewBag.Key;
var searchingKey = ViewBag.searchingkey;
var skip = ViewBag.skip;
}
<div class="destination_pics">
<div class="row">
#if (productList.Count>0)
{
int count = 0;
foreach (var item in productList)
{
if (count == 0)
{
<div class="col-sm-8">
<div class="highlights">
<a href="#Url.Action("tourdetail", "customer",new {key = QueryStringManager.Encrypt(item.ID)})">
<div class="highlithsTxt"> <p><strong>$#item.OnlinePrice</strong></p> <p>#item.ProductDisplayName</p> </div>
<img class="img-fluid" src="#item.ProductImage">
</a>
</div>
</div>
}
else if (count > 0 && count <= 2)
{
if (count == 1)
{
#:<div class="col-sm-4">
}
<div class="highlights">
<a href="#Url.Action("tourdetail", "customer",new {key = QueryStringManager.Encrypt(item.ID)})">
<div class="highlithsTxt"> <p><strong>$#item.OnlinePrice</strong></p> <p>#item.ProductDisplayName</p> </div>
<img class="img-fluid" src="#item.ProductImage">
</a>
</div>
if (count == 2)
{
#:</div>
<div class="clearfix"></div>
}
}
else if (count > 2 && count <= 5)
{
<div class="col-sm-4">
<div class="highlights">
<a href="#Url.Action("tourdetail", "customer",new {key = QueryStringManager.Encrypt(item.ID)})">
<div class="highlithsTxt"> <p><strong>$#item.OnlinePrice</strong></p> <p>#item.ProductDisplayName</p> </div>
<img class="img-fluid" src="#item.ProductImage">
</a>
</div>
</div>
}
else if (count > 5 && count <= 8)
{
<div class="col-sm-4">
<div class="card activityBox activeBox">
<a href="#Url.Action("tourdetail","customer",new {key = QueryStringManager.Encrypt(item.ID)})">
<div class="dealTags">
<div class="tag-spcial">Special Offer</div>
</div>
<img class="card-img-top" src="#item.ProductImage" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">#item.ProductDisplayName</h5>
<div class="row">
<div class="col-md-4 dealPrice">
<label>From</label>
$#item.OnlinePrice <span>$30.00</span>
</div>
<div class="col-md-5 dealLocation"><label>Location</label>#item.DestinationName</div>
<div class="col-md-3 favIt"><i class="far fa-heart"></i></div>
</div>
</div>
</a>
</div>
</div>
}
else if (count > 8 && count < 12)
{
<div class="col-sm-4">
<div class="card activityBox">
<a href="#Url.Action("tourdetail","customer",new {key = QueryStringManager.Encrypt(item.ID)})">
<div class="dealTags">
<div class="tag-spcial">Special Offer</div>
</div>
<img class="card-img-top" src="#item.ProductImage" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">#item.ProductDisplayName</h5>
<div class="row">
<div class="col-md-4 dealPrice">
<label>From</label>
$#item.OnlinePrice <span>$30.00</span>
</div>
<div class="col-md-5 dealLocation"><label>Location</label>#item.DestinationName</div>
<div class="col-md-3 favIt"><i class="far fa-heart"></i></div>
</div>
</div>
</a>
</div>
</div>
}
count++;
}
if (ViewBag.productCount > 12)
{
skip += 12;
<div class="clearfix"></div>
<div class="loadMore"> Load More Results</div>
}
}
</div>
</div>
</div>
In this view, I'd declared a list on the top as it is initialized at every and I want to declare it as static so that the earlier data should not be lost.
Here is my controller.
public ActionResult destination(string key, string searchingkey, FilterDataViewModel model, int skip = 0)
{
TempData["HeaderColor"] = true;
if (!string.IsNullOrEmpty(key))
{
int destinationId = QueryStringManager.Decrypt(key);
var destinationInfo = _masterRepo.GetMasterDataByID(destinationId);
var productList = _websiteRepo.GetAllProductListByDestinationId(destinationId).OrderByDescending(x => x.DestinationWeightPriority).ToList();
if (model.DestinationCityID > 0)
{
productList = (from prod in productList where prod.DestinationCity == model.DestinationCityID select prod).ToList();
}
ViewBag.productCount = productList.Count();
var a = productList.Skip(skip).Take(12).ToList();
ViewBag.ProductList = productList.Skip(skip).Take(12).ToList();
var allAdbyDestination = _websiteRepo.GetAllAdvertisementList(destinationId);
ViewBag.allDestinationAd = allAdbyDestination;
ViewBag.DestinationName = destinationInfo.MasterData;
ViewBag.DestinationImages = destinationInfo.ImagePath;
var categoryID = MasterConstant.GetCategoryID(CatergoryConstant.City);
var allDestinationCity = _masterRepo.GetMasterDataByCategoryIDandXrefID(categoryID, destinationId);
ViewBag.DestinationCityList = new SelectList(allDestinationCity, "ItemID", "MasterData");
ViewBag.Key = key;
ViewBag.searchingkey = searchingkey;
ViewBag.skip = skip;
return View(a);
}
else
{
return RedirectToAction("index", "home");
}
}
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.