How to show images on an HTML page - c#

I am developing a ASP.NET MVC 4 web api to show product image associated with a company. In the database I have stored CompanyID & CompanyProductImageURL or CompanyProductImageFilepath. Now using my web api, when I click on 'Show Image' button, I want to show the product image on the same page. Right now, the url is localhost:1111/ViewCompanyProductImage.html ; when I enter CompanyID =31 & click on 'Show Image' button new tab opens with url http://localhost:1111/api/Images/?CompanyID=31 and then the CompanyProductImageURL or CompanyProductImageFilepath associated with that Company opens in another tab. I want the image to show up in localhost:1111/ViewCompanyProductImage.html under the 'SHow Image' button. Here's the code I have.
webapiconfig.cs
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "ImagesApi",
routeTemplate: "api/Images/{companyid}"
defaults: new { Controller = "Images", companyid = #"\d+" }
);}
----Controller
public class ImagesController : ApiController
{
private static T ConvertFromDBVal<T>(object obj)
{
if (obj == null || obj == DBNull.Value)
{
return default(T); // returns the default value for the type
}
else
{
return (T)obj;
}
}
[System.Web.Http.AcceptVerbs("GET")]
public HttpResponseMessage Get(int companyid)
{
Images oldImages = new Images();
string sql = "select companyid,companyproducturl from [dbo].[CompanyImage] WHERE companyid = #companyid";
using (SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["connection"].ConnectionString))
{
using (SqlCommand query = new SqlCommand(sql, connection))
{
SqlDataReader rdr;
query.Parameters.Add(new SqlParameter("#companyid", companyid));
query.CommandType = CommandType.Text;
connection.Open();
query.CommandTimeout = 90;
rdr = query.ExecuteReader();
if (rdr != null)
{
while (rdr.Read())
{
oldImages.companyid = ConvertFromDBVal<int>(rdr["companyid"]);
oldImages.companyproducturl = ConvertFromDBVal<string>(rdr["companyproducturl"]);
}
}
}
}
if (oldImages.companyid == 0 )
{
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, String.Format("No records found for companyid: {0} ", companyid)));
}
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
System.Diagnostics.Process.Start(oldImages.imageproducturl);
return response;
}
---view
public class Images
{
[Required(AllowEmptyStrings = false, ErrorMessage = "companyid Required")]
[Range(1, 10000)]
public int companyid { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "imageproducturl Required")]
public string companyproducturl { get; set; }
}
--index.cshtml
<div id="body">
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1> Web API!</h1>
</hgroup>
</div>
</section>
<section class="content-wrapper main-content clear-fix">
<p>
For API documentation: #Html.ActionLink("API", "Index", "Help", new { area = "" }, null)
</p>
<p>
View Company Images:Click Here!
</p>
</section>
</div>
--ViewCompanyProductImage.html
<div class="jumbotron" align="center">
<h1>Images Web API</h1>
<p class="lead"></p>
</div>
<div class="row">
<div class="col-md-4" align="center">
<div class="first" align="center">
<form action="api/Images/" method="get" target="_blank">
companyid:
<br />
<input type="text" name="companyid"><br>
<td>
<input type="submit" value="Show Image" />
</form>
</div>
</div>
</div>
How can I show product image on the localhost:1111/ViewCompanyProductImage.html itself?
Thanks
R

You can do this using JavaScript.
Place an image element on the page, give it an ID and on button click, instead of submit, find the image element and set its src property to the desired URL.
<img src="" id="companyImage" />
<input type="text" name="companyid" />
<input type="button" value="Show Image" onclick="previewImage" />
And then in JS:
function previewImage() {
var companyId = getElementById('companyid').value;
getElementById('companyImage').src = "api/Images/?companyID=" + companyId;
}

Related

After filtering/sorting how to make the pagination not reset to page 1 but stay at current page?

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);
}

How to retrieve old Path image when we not update c# mvc

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>

Error: No parameterless constructor defined for this object

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.

Cascading Drop Down in ASP.NET Core using Razor and jQuery

I've been trying to populate two dropdown list from my database. The first one is populated on form load, and I want to fill the second after the user selects a value in the first one.
I have followed and adapted this tutorial. But with no luck.
My Controller
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Oracle.ManagedDataAccess.Client;
using MaterialProjectMaterials.Models;
using UserProfile.Models;
using System.Data;
using Microsoft.AspNetCore.Http;
namespace MaterialProject.Controllers
{
public class MaterialsController : Controller
{
private readonly OracleConnection con = new OracleConnection(GetConString.ConString());
public IActionResult Materials()
{
List<Brands> brandslist = new List<Brands>();
brandslist.Insert(0, new Brands { BCodeID = 0, BDescr = "--Select Brand--" });
//Getting Data from Database using EntityFrameworkCore
con.Open();
string b_query = "SELECT codeID, descr FROM itemcategory WHERE codeID LIKE ('3%') AND LENGTH(codeID)= 3 and rownum<=2 ORDER BY descr";
OracleCommand b_cmd = new OracleCommand(b_query, con);
OracleDataAdapter b_da = new OracleDataAdapter(b_cmd);
DataTable b_dt = new DataTable();
b_da.Fill(b_dt);
foreach (DataRow b_rb in b_dt.Rows)
{
brandslist.Add(new Brands
{
BCodeID = Convert.ToInt64(b_rb["codeID"]),
BDescr = b_rb["descr"].ToString()
});
}
con.Close();
ViewBag.BrandsList = brandslist;
return View();
}
[HttpPost]
public IActionResult Materials(Brands objbrand, FormCollection formCollection)
{
//Validation
if (objbrand.BCodeID == 0)
ModelState.AddModelError("", "Select Brand");
else if (objbrand.VCodeID == 0)
ModelState.AddModelError("", "Select Volume");
//Getting selected Value
var BCodeID = HttpContext.Request.Form["BCodeID"].ToString();
var VCodeID = HttpContext.Request.Form["VCodeID"].ToString();
//Setting Data back to ViewBag after Posting Form
List<Brands> brandslist = new List<Brands>();
brandslist.Insert(0, new Brands { BCodeID = 0, BDescr = "--Select Brand--" });
//Getting Data from Database
con.Open();
string b_query = "SELECT codeID, descr FROM itemcategory WHERE codeID LIKE ('3%') AND LENGTH(codeID)= 3 ORDER BY descr";
OracleCommand b_cmd = new OracleCommand(b_query, con);
OracleDataAdapter b_da = new OracleDataAdapter(b_cmd);
DataTable b_dt = new DataTable();
b_da.Fill(b_dt);
foreach (DataRow b_rb in b_dt.Rows)
{
brandslist.Add(new Brands
{
BCodeID = Convert.ToInt64(b_rb["codeID"]),
BDescr = b_rb["descr"].ToString()
});
}
con.Close();
//Assing BCodeID to ViewBag.BrandsList
ViewBag.BrandsList = brandslist;
return View(objbrand);
}
public JsonResult GetVolumes(Int64? BCodeID)
{
if (BCodeID == null)
{
throw new ArgumentNullException(nameof(BCodeID));
}
List<Volume> volumelist = new List<Volume>();
volumelist.Insert(0, new Volume { VCodeID = 0, VDescr = "--Select Volume--" });
//Getting Data from Database
con.Open();
string v_query = "SELECT DISTINCT IG.CODEID, IG.DESCR FROM MATERIAL M INNER JOIN ITEMGROUP IG ON M.IGPID = IG.CODEID INNER JOIN ITEMCATEGORY IC ON '3' || SUBSTR(M.ICTID, 3, 2) = IC.CODEID WHERE M.ICTID LIKE('3%') AND IC.CODEID =" + BCodeID + "ORDER BY CODEID";
OracleCommand v_cmd = new OracleCommand(v_query, con);
OracleDataAdapter v_da = new OracleDataAdapter(v_cmd);
DataTable v_dt = new DataTable();
v_da.Fill(v_dt);
foreach (DataRow v_dr in v_dt.Rows)
{
volumelist.Add(new Volume
{
VCodeID = Convert.ToInt64(v_dr["codeID"]),
VDescr = v_dr["descr"].ToString()
});
}
con.Close();
return Json(new SelectList(volumelist, "VCodeID", "VDescr"));
}
}
}
My View
#model MaterialProjectMaterials.Models.Brands
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#{
<script src="~/lib/jquery/dist/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var items = "<option value='0'>--Select Volume--</option>";
$("VCodeID").html(items);
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#BCodeID").change(function () {
var url = '#Url.Content("~/")' + "Materials/GetVolumes";
var ddlsource = "#BCodeID";
$.getJSON(url, { BCodeID: $(ddlsource).val() }, function (data) {
var items = '';
$("#VCodeID").empty();
$.each(data, function (i, volume) {
items += "<option value='" + volume.value + "'>" + volume.text + "</option>";
});
$("#VCodeID").html(items);
});
})
})
</script>
<form asp-controller="Materials" asp-action="Materials" method="post" class="form-horizontal" role="form">
<div class="form-group">
<div class="row">
<div class="alert-danger" asp-validation-summary="ModelOnly"></div>
<div class="col-xs-12 col-sm-6 col-lg-4">
<label asp-for="BDescr" class="control-label">Brands</label>
<select asp-for="BCodeID" class="form-control"
asp-items="#(new SelectList(ViewBag.BrandsList, "BCodeID", "BDescr"))"></select>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-xs-12 col-sm-6 col-lg-4">
<label class="control-label">Volume</label>
<select class="form-control" id="vCodeID" name="vDescr" asp-for="VCodeID"
asp-items="#(new SelectList(string.Empty, "VCodeID", "VDescr"))"></select>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-xs-12 col-sm-6 col-lg-4">
<input id="Submit1" type="submit" value="Submit" />
</div>
</div>
</div>
</form>
}
My Models
namespace MaterialProjectMaterials.Models
{
public class MaterialsModel
{
public DbSet<Brands> Brands { get; set; }
public DbSet<Volume> Volume { get; set; }
}
}
namespace MaterialProjectMaterials.Models
{
[Table("ITEMCATEGORY")]
public class Brands
{
[Key]
[Column("CODEID")]
public Int64 BCodeID { get; set; }
[Column("DESCR")]
public string BDescr { get; set; }
[NotMapped]
public Int64 VCodeID { get; set; }
}
}
namespace MaterialProjectMaterials.Models
{
[Table("IT_MATERIAL_VOLUMES")]
public class Volume
{
[Key]
[Column("VCODEID")]
public Int64 VCodeID { get; set; }
[Column("VDESCR")]
public string VDescr { get; set; }
[Column("BDESCR")]
public int BCodeID { get; set; }
}
}
The result when I run the project is that I can get the values in the first dropdownlist, but when I select a value I did not get anything back to the second dropdownlist.
I would appreciate any help.
Thanks in advance.
Update 1
In the debugger I get the follows error concerning the javascrips
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:44373/lib/jquery/jquery.js
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 3.5252ms 404
Unhandled exception at line 4, column 9 in https://localhost:44373/Home/Login
0x800a1391 - JavaScript runtime error: '$' is undefined
as for the line
Unhandled exception at line 4, column 9 in https://localhost:44373/Home/Login
it says that the script locate at ~/Home/Login but my script are at ~/Materials/Materials
Finally my .js files are locate at
~\MaterialProject\wwwroot\lib\jquery
Any help would appreciate a lot!
Update 2
I solve my problem
I use instead of and also I replace
<div class="form-group">
<div class="row">
<div class="col-xs-12 col-sm-6 col-lg-4">
<label class="control-label">Volume</label>
<select class="form-control" id="vCodeID" name="vDescr" asp-for="VCodeID"
asp-items="#(new SelectList(string.Empty, "VCodeID", "VDescr"))"></select>
</div>
</div>
</div>
with
<div class="form-group">
<div class="row">
<div class="col-xs-12 col-sm-6 col-lg-4">
<label asp-for="VDescr" class="control-label">Volume</label>
<select asp-for="VCodeID" class="form-control"
asp-items="#(new SelectList(string.Empty, "VCodeID", "VDescr"))"></select>
</div>
</div>
</div>

FormCollection Empty in ASP.NET Mobile View

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.

Categories

Resources