In my MVC application I allow users to add an object to a database table through a "Create" controller/view using Entity Framework database first design. When testing I have no data in this table currently so the first object should have an ID of 1.
But in the view, the field for ID is empty. Again, it should be 1 since this is the first object and it's picking up from the data model. The next time they add another object, the ID should be 2...etc.
I have set IsIdentity to Yes. I have set Identity seed to 1.
Programatically what am I missing for the ID field to display 1 when this is the first item to be added to the table.
View
<div class="form-group">
#Html.LabelFor(model => model.ProductId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ProductId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ProductId, "", new { #class = "text-danger" })
</div>
</div>
Controller
// GET: Products/Create
public ActionResult Create()
{
return View();
}
// POST: Products/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ProductId,...Other columns")] Product product)
{
if (ModelState.IsValid)
{
db.Products.Add(product);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(product);
}
Model
public int ProductId { get; set; }
SQL
[dbo].[Product]
(
[ProductId] [INT] IDENTITY(1,1) NOT NULL
)
https://i.stack.imgur.com/fGa3i.png
Related
I tried to save records of multiple products in a table, in database, with a single form but, there is this error and I don't know hot to solve it.
Error: Array to string conversion
in vendor\laravel\framework\src\Illuminate\Support\Str
$result .= (array_shift($replace) ?? $search).$segment;
Datatype of 'reference' and 'quantity' is string.
This is view:
<form action="{{route('carts.store')}}" method="post">
#csrf
#foreach(session('cart') as $id => $details)
<div class="form-group">
<input type=hidden class="form-control" name="reference[]" id="referenceNumber" value="{{ $details['reference'] }}">
</div>
<div class="form-group">
<input type=hidden class="form-control quantity" name="quantity[]" value="{{$details['quantity']}}" id="productPrice">
</div>
#endforeach
<button type="submit" class="btn btn-primary">Add products</button>
</form>
This is controller:
public function store(Request $request)
{
$cart = new Cart;
$data = [
'reference' => $request->reference,
'quantity' => $request->quantity
];
$cart->fill($data);
$cart->save();
return view('riepilogo');
}
When I click on button "add products" only the last records is saved in table
class Cart extends Model
{
protected $fillable = ['id', 'reference', 'pdv_code', 'quantity'];
public $timestamps = false;
public function product()
{
return $this->belongsToMany('App\Product');
}
}
class Product extends Model
{
protected $fillable = ['ean', 'reference', 'product_price', 'pdv_code'];
public $timestamps = false;
public function detail()
{
return $this->belongsTo('App\Products_detail');
}
public function cart()
{
return $this->belongsToMany('App\Cart');
}
}
> Blockquote
Migration:
public function up()
{
Schema::create('cart_product', function (Blueprint $table) {
$table->unsignedBigInteger('cart_id');
$table->foreign('cart_id')
->references('id')
->on('carts')
->onDelete('cascade');
$table->unsignedBigInteger('product_id');
$table->foreign('product_id')
->references('id')
->on('products')
->onDelete('cascade');
$table->primary(['cart_id', 'product_id']);
});
}
public function down()
{
Schema::dropIfExists('cart_product');
}
Migration cart:
public function up()
{
Schema::create('carts', function (Blueprint $table) {
$table->id();
$table->char('reference');
$table->integer('quantity');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('carts');
}
public function addToCart(Request $request, $id, $reference)
{
$product = Product::find($id)->where('reference', $reference)->first();
if(!$product) {
abort(404);
}
$cart = session()->get('cart');
// if cart is empty then this the first product
if(!$cart) {
$cart = [
$id => [
"id" => $product->id,
"quantity" => 1,
"price" => $product->product_price,
"ean" => $product->ean,
"reference" => $product->reference
]
];
//dd($cart);
session()->put('cart', $cart);
return back()->with('success', 'Product added to cart successfully!');
}
// if cart not empty then check if this product exist then increment quantity
if(isset($cart[$id])) {
$cart[$id]['quantity']++;
session()->put('cart', $cart);
return back()->with('success', 'Product added to cart successfully!');
}
// if item not exist in cart then add to cart with quantity = 1
$cart[$id] = [
"id" => $product->id,
"quantity" => 1,
"price" => $product->product_price,
"ean" => $product->ean,
'reference' => $product->reference
];
session()->put('cart', $cart);
return back()->with('success', 'Product added to cart successfully!');
}
Your form should have a reference to the cart via the id for both input fields
<form action="{{route('carts.store')}}" method="post">
#csrf
#foreach(session('cart') as $id => $details)
<div class="form-group">
<input type=hidden class="form-control" name="{{ 'cart_items[' .$id . '][reference]' }}" id="referenceNumber" value="{{ $details['reference'] }}">
</div>
<div class="form-group">
<input type=hidden class="form-control quantity" name="{{ 'cart_items[' . $id . '][quantity]' }}" value="{{$details['quantity']}}" id="productPrice">
</div>
#endforeach
<button type="submit" class="btn btn-primary">Add products</button>
</form>
$request->input('cart_items') will give the array of all products added to the cart
And you need another model CartItem and table cart_items to store the line items for the cart where each line can have a product_id and quantity at the very least.
Or you can add the quantity and price column on the cart_product pivot table.
For the carts table: you can have columns: total, tax etc the product reference and quantity columns can't be on carts table its of no use - a cart can have 3 products added for example to it [Tshirt: 1, Trouser: 2, Hoodie: 1] now which reference and which product's quantity will get stored in the carts table?
Instead there can be three records for cart_items table
Tshirt->id, quantity, cart_id
Trouser-id, quantity, cart_id
Hoodie->id, quantity, cart_id
I am using this code
var parent = ContentReference.StartPage;
IContentRepository contentRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentRepository>();
PageData myPage = contentRepository.GetDefault<LoginPage>(parent);
myPage.PageName = "My new page";
var page = contentRepository.GetChildren<LoginPage>(parent).FirstOrDefault(name => name.Name == myPage.Name);
if (page == null)
contentRepository.Save(myPage, EPiServer.DataAccess.SaveAction.Publish);
to create a page programatically. The thing is I am not sure where to put this code?
I don't want to show LoginPage which is page type to show in the list in the admin/edit panel as I want to create only one page under that page type. Maybe there is another way where I can just create a stand alone page and don't have to create the page type or maybe use an already made page type.
This is the code for my page type
[ContentType(DisplayName = "Custom Login Page", GUID = "c0d358c3-4789-4e53-bef3-6ce20efecaeb", Description = "")]
public class LoginPage : StandardPage
{
/*
[CultureSpecific]
[Display(
Name = "Main body",
Description = "The main body will be shown in the main content area of the page, using the XHTML-editor you can insert for example text, images and tables.",
GroupName = SystemTabNames.Content,
Order = 1)]
public virtual XhtmlString MainBody { get; set; }
*/
}
Then I am creating a model like this
public class LoginModel : PageViewModel<LoginPage>
{
public LoginFormPostbackData LoginPostbackData { get; set; } = new LoginFormPostbackData();
public LoginModel(LoginPage currentPage)
: base(currentPage)
{
}
public string Message { get; set; }
}
public class LoginFormPostbackData
{
public string Username { get; set; }
public string Password { get; set; }
public bool RememberMe { get; set; }
public string ReturnUrl { get; set; }
}
And my controller looks like this
public ActionResult Index(LoginPage currentPage, [FromUri]string ReturnUrl)
{
var model = new LoginModel(currentPage);
model.LoginPostbackData.ReturnUrl = ReturnUrl;
return View(model);
}
Do you think there is another way to do it? I will also show my login view
#using EPiServer.Globalization
#model LoginModel
<h1 #Html.EditAttributes(x =>
x.CurrentPage.PageName)>#Model.CurrentPage.PageName</h1>
<p class="introduction" #Html.EditAttributes(x =>
x.CurrentPage.MetaDescription)>#Model.CurrentPage.MetaDescription</p>
<div class="row">
<div class="span8 clearfix" #Html.EditAttributes(x =>
x.CurrentPage.MainBody)>
#Html.DisplayFor(m => m.CurrentPage.MainBody)
</div>
#if (!User.Identity.IsAuthenticated &&
!User.IsInRole("rystadEnergyCustomer"))
{
<div class="row">
#using (Html.BeginForm("Post", null, new { language = ContentLanguage.PreferredCulture.Name }))
{
<div class="logo"></div>
#Html.AntiForgeryToken()
<h2 class="form-signin-heading">Log in</h2>
#Html.LabelFor(m => m.LoginPostbackData.Username, new { #class = "sr-only" })
#Html.TextBoxFor(m => m.LoginPostbackData.Username, new { #class = "form-control", autofocus = "autofocus" })
#Html.LabelFor(m => m.LoginPostbackData.Password, new { #class = "sr-only" })
#Html.PasswordFor(m => m.LoginPostbackData.Password, new { #class = "form-control" })
<div class="checkbox">
<label>
#Html.CheckBoxFor(m => m.LoginPostbackData.RememberMe)
#Html.DisplayNameFor(m => m.LoginPostbackData.RememberMe)
</label>
</div>
#Html.HiddenFor(m => m.LoginPostbackData.ReturnUrl, "/login-customers")
<input type="submit" value="Log in" class="btn btn-lg btn-primary btn-block" />
}
#Html.DisplayFor(m => m.Message)
</div>
}
else
{
<span>Welcome #User.Identity.Name</span>
#Html.ActionLink("Logout", "Logout", "LoginPage", null, null);
}
I think you're misunderstanding some of the Episerver concepts.
If you don't want it to be a page in Episerver, you shouldn't use PageController, page types, or templates. Instead, just use a standard controller and view to create your login page.
Otherwise, you do have to create a page of type LoginPage, which will be visible in the page tree. No need to create it programmatically, you can just add the page manually and then hide the LoginPage type from edit mode to avoid editors creating additional login pages.
As said, i'm trying to insert an image in a table, where the type of the field is Varbinary.
What i've done so far :
I've a form with many fields:
#using (Html.BeginForm("InsertProduct", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>PRODUCT</legend>
<div class="editor-label">
#Html.LabelFor(model => model.PRODUCT_ID)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PRODUCT_ID)
#Html.ValidationMessageFor(model => model.PRODUCT_ID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PRODUCT_NAME)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PRODUCT_NAME)
#Html.ValidationMessageFor(model => model.PRODUCT_NAME)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PRODUCT_IMAGE)
</div>
<div class="editor-field">
<input type="file" name="PRODUCT_IMAGE" id="PRODUCT_IMAGE" style="width: 100%;" />
</div>
<p>
<input type="submit" value="Create" class="btn btn-primary"/>
</p>
</fieldset>
}
And all these fields allow me to construct a PRODUCT object in my controller :
public ActionResult InsertProduct(PRODUCT ord)
{
MigrationEntities1 sent = new MigrationEntities1();
sent.PRODUCT.Add(ord);
sent.SaveChanges();
List<PRODUCT> Products = sent.PRODUCT.ToList();
return View("Products", Products);
}
But when i'm trying to upload the image (by clicking on Create button), i've the following :
entry is not a valid base64 string because it contains a character
that is not base 64
So first of all : is it the right way to deal with images and second, I think I need to do a pre-treatemant on my image to insert it : how to o that ?
Thanks !
Edit :
Thanks to answers received, seems to be good for insertion. But for displaying, I still have issues (only the "not found image" piture is displayed). I've try to do it two ways :
1.
<img src="LoadImage?id=#Model.product.PRODUCT_ID"/>
and in the controller
public Image LoadImage(int id)
{
String serviceAddress = ConfigurationManager.AppSettings["WCFADDRESS"];
DataServiceContext context = new DataServiceContext(new Uri(serviceAddress));
PRODUCT product = context.Execute<PRODUCT>(new Uri(serviceAddress + "prod_id?prod_id=" + id)).ToList().FirstOrDefault();
MemoryStream ms = new MemoryStream(product.PRODUCT_IMAGE);
Image img = Image.FromStream(ms);
return img;
}
And 2. :
#{
if (Model.product.PRODUCT_IMAGE != null)
{
WebImage wi = new WebImage(Model.product.PRODUCT_IMAGE);
wi.Resize(700, 700,true, true);
wi.Write();
}
}
But none of them are working. What am I doing wrong ?
1) Change your database table to have these columns:
1: ProductImage - varbinary(MAX)
2: ImageMimeType - varchar(50)
2) Change your action method like this:
public ActionResult InsertProduct(PRODUCT ord,
HttpPostedFileBase PRODUCT_IMAGE)
{
if (ModelState.IsValid)
{
MigrationEntities1 sent = new MigrationEntities1();
if (image != null)
{
ord.ProductImage= new byte[PRODUCT_IMAGE.ContentLength];
ord.ImageMimeType = PRODUCT_IMAGE.ContentType;
PRODUCT_IMAGE.InputStream.Read(ord.ProductImage, 0,
PRODUCT_IMAGE.ContentLength);
}
else
{
// Set the default image:
Image img = Image.FromFile(
Server.MapPath(Url.Content("~/Images/Icons/nopic.png")));
MemoryStream ms = new MemoryStream();
img.Save(ms, ImageFormat.Png); // change to other format
ms.Seek(0, SeekOrigin.Begin);
ord.ProductImage= new byte[ms.Length];
ord.ImageMimeType= "image/png";
ms.Read(ord.Pic, 0, (int)ms.Length);
}
try
{
sent.PRODUCT.Add(ord);
sent.SaveChanges();
ViewBag.HasError = "0";
ViewBag.DialogTitle = "Insert successful";
ViewBag.DialogText = "...";
}
catch
{
ViewBag.HasError = "1";
ViewBag.DialogTitle = "Server Error!";
ViewBag.DialogText = "...";
}
List<PRODUCT> Products = sent.PRODUCT.ToList();
return View("Products", Products);
}
return View(ord);
}
This action method is just for create. you need some works for edit and index too. If you have problem to doing them, tell me to add codes of them to the answer.
Update: How to show images:
One way to show stored images is as the following:
1) Add this action method to your controller:
[AllowAnonymous]
public FileContentResult GetProductPic(int id)
{
PRODUCT p = db.PRODUCTS.FirstOrDefault(n => n.ID == id);
if (p != null)
{
return File(p.ProductImage, p.ImageMimeType);
}
else
{
return null;
}
}
2) Add a <img> tag in the #foreach(...) structure of your view (or wherever you want) like this:
<img width="100" height="100" src="#Url.Action("GetProductPic", "Products", routeValues: new { id = item.ID })" />
Change the Image type on the sql sever to Byte[] and use something like this. This is how I have stored images in the past.
http://www.codeproject.com/Articles/15460/C-Image-to-Byte-Array-and-Byte-Array-to-Image-Conv
If not, you can always just store the image locally and pass the image location through a string into the SQL data base, this method works well and is quick to set up.
So, here are the modifications to do :
To insert data in the database :
[HttpPost]
public ActionResult InsertProduct(PRODUCT ord, HttpPostedFileBase image)
{
MigrationEntities1 sent = new MigrationEntities1();
if (image != null)
{
ord.PRODUCT_IMAGE = new byte[image.ContentLength];
image.InputStream.Read(ord.PRODUCT_IMAGE, 0, image.ContentLength);
}
sent.PRODUCT.Add(ord);
sent.SaveChanges();
List Products = sent.PRODUCT.ToList();
return View("Products", Products);
}
Note: this is the "light" way, for something that is more complete, have a look to Amin answer.
For displaying :
In the view
<img src="LoadImage?id=#Model.product.PRODUCT_ID"/>
And in the controller :
public FileContentResult LoadImage(int id)
{
String serviceAddress = ConfigurationManager.AppSettings["WCFADDRESS"];
DataServiceContext context = new DataServiceContext(new Uri(serviceAddress));
PRODUCT product = context.Execute<PRODUCT>(new Uri(serviceAddress + "prod_id?prod_id=" + id)).ToList().FirstOrDefault();
return new FileContentResult(product.PRODUCT_IMAGE, "image/jpeg");
}
And everything is ok now, thanks !
I have searched around for a while now with no joy. I am trying to save an image to my SQL db as a byte array, then I am trying to display it later. The display part is not working. I don't know if it's a problem with the save or the display. The save appears to be working ok, I can see 'Binary Data' in my SQL table. Any suggestions?
What's happening is that I get a broken image icon on my page. Even if I manually goto the URL e.g. .../Treatments/LoadImage/14 it's broken.
Model contains this in my table definition:
public byte[] Photo { get; set; }
Create View:
<div class="editor-label">
#Html.LabelFor(model => model.Photo)
</div>
<div class="editor-field">
<input type="file" name="photo" />
</div>
Create Controller:
[HttpPost]
public ActionResult Create([Bind(Exclude = "Photo")]Treatment treatment)
{
if (ModelState.IsValid)
{
treatment.Photo = GetByteArrayFromFile();
treatment.WebOrder = db.Treatments.Count();
db.Treatments.Add(treatment);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.TreatmentTypeId = new SelectList(db.TreatmentTypes, "Id", "Name", treatment.TreatmentTypeId);
return View(treatment);
}
private byte[] GetByteArrayFromFile() {
int fileLength = Request.Files["photo"].ContentLength;
byte[] byteArray = new byte[fileLength];
return byteArray;
}
Display View:
<div class="display-label">
#Html.DisplayNameFor(model => model.Photo)
</div>
<div class="display-field">
<img src="#Url.Action("LoadImage", new { Id = Model.Id })" />
</div>
LoadImage Controller:
public ActionResult LoadImage(int Id) {
byte[] bytes = db.Treatments.Find(Id).Photo;
return File(bytes, "image/jpeg");
}
I have added:
#using (Html.BeginForm("Create", "Treatments", FormMethod.Post, new { enctype = "multipart/form-data" })) {
// View Code Omitted
}
to my Create view.
Is there something elementary wrong with my code? Any suggestions? Thanks.
It was a problem with my GetByteArrayFromFile Method. My original method above returned an array of zeros only. Using this, I fixed my issue:
private byte[] GetByteArrayFromFile() {
WebImage image = WebImage.GetImageFromRequest();
byte[] byteArray = image.GetBytes();
return byteArray;
}
I have been googling for a solution to my problem for two days without any luck. Can any stars in MVC3 .NET help?
I am trying to build an .NET MVC3 application to update images saved in an database.
Here is the action method
[HttpPost]
public ActionResult Edit(myImage img, HttpPostedFileBase imageFile)
{
//var img = (from imga in db.myImages
// where imga.imageID == id
// select imga).First();
if (ModelState.IsValid)
{
if (img != null)
{
img.imageType = imageFile.ContentType;
img.Data = new byte[imageFile.ContentLength];
imageFile.InputStream.Read(img.Data, 0, imageFile.ContentLength);
}
// save the product
UpdateModel(img);
db.SubmitChanges();
return RedirectToAction("Index");
}
else
{
// there is something wrong with the data values
return View(img);
}
}
Here is the view
#model JackLing.Models.myImage
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Edit</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm("Edit", "Image",FormMethod.Post, new { enctype = "multipart/form-data" })){
#Html.ValidationSummary(true)
<fieldset>
<legend>myImage</legend>
#Html.EditorForModel();
<div class="editor-label">Image</div>
<div class="editor-field">
#if (Model.Data != null)
{
<img src="#Url.Action("show", new { id = Model.imageID })" height="150" width="150" />
}
else {
#:None
}
</div>
<p>
<span>Choose a new file</span> <input type="file" name="imgFile"/>
</p>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
When I run the application it throws an error saying "Object reference not set to an instance of an object."
Any suggestions on how to fix the problems will be appriciated! By the way, the create and details method are all working. I think it has to do with data binding, but I'm not sure... I have no clue how to fix it.
Finally fixed the problem based on the advice from Eulerfx
here is the working action.
[HttpPost]
public ActionResult Edit(myImage img, HttpPostedFileBase imageFile)
{
myImage imgToSave = (from imga in db.myImages
where imga.imageID == img.imageID
select imga).First();
if (ModelState.IsValid)
{
if (img != null)
{
imgToSave.imageType = imageFile.ContentType;
var binaryReader = new BinaryReader(imageFile.InputStream);
imgToSave.Data = binaryReader.ReadBytes(imageFile.ContentLength);
binaryReader.Close();
}
TryUpdateModel(imgToSave);
db.SubmitChanges();
return RedirectToAction("Index");
}
else
{
// there is something wrong with the data values
return View(img);
}
}
The problem may be that the name of the file input field in the HTML is imgeFile and the name of the file parameter in MVC is imageFile. Ensure that the input field name and the action method parameter names match.