Every row is executed twice - visual-studio

I have found a bug - and I haven't found any solution to this.
I have a code in ASP.NET Core (using VSPro 2019 16.5.0):
public IActionResult CreateSubGroup(MyClass model, string returnUrl = null)
{
if (ModelState.CreateMyClassValidation())
{
if (!db.MyClass.Where(x => x.Title == model.Title).Any())
{
ViewData["ReturnUrl"] = returnUrl;
var code = new MyClass { Title = model.Title, IdGroup = model.IdGroup, GroupCode = model.GroupCode};
db.MyClass.Add(code);
var result = db.SaveChanges();
if (result > 0)//if there was no issue (at least one row was changed)
{
this.AddNotification(MessagesHandler.Success, $"Item\"{model.Title}\" was successfully created.");
}
else
{
this.AddNotification(MessagesHandler.Error, $"Item \"{model.Title}\" cannot be created.");
}
}
else
{
this.AddNotification(MessagesHandler.Error, $"Item \"{model.Title}\" already exists.");
}
}
else
{
this.AddNotification(MessagesHandler.Error, $"ErrorMessage.");
}
return RedirectToLocal(returnUrl);
}
Creating of new Item always crashes with unique code exception from DB - During debuging I have found, that every row is executed twice (and I don't know why??) - so also the row db.SaveChanges() is executed twice and that's why I got this exception.
Second bad thing is, that not even the first attempt to save database is not executed (= new Item is not created in DB).
Have you seen this error?
EDIT:
I have found, that it happens only when data are posted from view with JS/AJAX (from modal window)
Here is the code for sending data:
<div class="modal fade" id="ModalWindow" tabindex="-1" role="dialog" aria-labelledby="ModalForm" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form id="ModalForm" action="" method="post" class="validator">
<div class="modal-body">
<div class="form-group">
<label asp-for="Id"></label>
<input class="form-control" asp-for="Id" value="" readonly data-val="false">
<div class="form-text text-muted small">ID cannot be changed!</div>
</div>
<div class="form-group">
<label asp-for="Title"></label>
<input class="form-control mlfb-create" asp-for="Title" placeholder="Title" value="" autofocus tabindex="#(++tabindex)">
<span class="text-danger small" asp-validation-for="Title"></span>
</div>
<div class="form-group">
<label asp-for="IdGroup"></label>
<select class="selectpicker form-control" asp-for="IdGroup" data-live-search="true" data-style="btn-info" tabindex="#(++tabindex)">
#if (data?.GroupData != null)
{
#foreach (var item in data?.GroupData)
{
<option value="#(item.Id)">#item.Title</option>
}
}
</select>
</div>
<div class="form-group">
<label asp-for="GroupCode"></label>
<input class="form-control mlfb-create" asp-for="GroupCode" placeholder="Title" value="" autofocus tabindex="#(++tabindex)">
<span class="text-danger small" asp-validation-for="GroupCode"></span>
</div>
</div>
<div class="text-center modal-footer">
<button type="submit" class="btn btn-success _modal-buttton-save" tabindex="#(++tabindex)"><i class="fas fa-check mr-2"></i><span>Save</span></button>
<button type="reset" class="btn btn-secondary" data-dismiss="modal"><i class="fas fa-times mr-2"></i>Cancel</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#section scripts {
<script>
$(function () {
"use strict";
$(document).on('click', '._createSubFormButton', function () {
$('#ModalWindow').modal('show');
$('.modal-title').text('Creating of subgroup');
$('.modal-buttton-save span').text('Create');
$('#ModalForm').attr('action', '/MyCode/CreateSubGroup/?returnurl=' + window.location.href);
});
// Edit form
$(document).on('click', 'tr ._editSubFormButton', function () {
$('#ModalWindow').modal('show');
var $tr = $(this).closest('tr');
var Id = $tr.find('._Id').text();
var Title = $tr.find('._Title').text();
var IdGroup = $tr.find('._IdGroup').text();
var GroupCode = $tr.find('._GroupCode').text();
$('.modal-title').text('Editing of subgroup');
$('#ModalForm').attr('action', '/MyCode/EditSubGroup/' + Id + '?returnurl=' + window.location.href);
$('#Id').val(Id);
$('#Title').val(Title);
$('#GroupCode').val(GroupCode);
});
// form validation reset during closing modal form
$('#ModalWindow').on('hidden.bs.modal', function () {
$(this).find('form').trigger('reset');
$('#IdGroup').load();
$('.form-group .is-invalid').each(function () { $(this).removeClass('is-invalid'); });
$('.form-group .is-valid').each(function () { $(this).removeClass('is-valid'); });
$('.form-text.text-danger').each(function () { $(this).removeClass('text-danger'); });
$('.form-text.text-success').each(function () { $(this).removeClass('text-success'); });
$('.invalid-feedback').each(function () { $(this).remove(); });
});
$(document).on('submit', '#ModalForm', function (e) {
var form = $('#ModalForm');
if (form.valid()) {
console.log(form.serializeArray());
$.ajax({
url: form.attr("action"),
type: form.attr("method"),
data: form.serializeArray()
}).done(function () {
console.log('done');
$tr.find('._Number').text();
var $tr = $(this).closest('tr');
})
.fail(function () {
console.log('fail');
});
$('#ModalWindow').modal('hide');
}
});
error I got:

Have you tried debugging this code? Debugging with setting breakpoints and stepping through the code would help you find what is wrong with this code.

Related

Laravel Ajax Add To Cart Not working 500 internal error

I have code I am working on. I will list the page, the route, and the controller code. When I inspect and click on the add to cart button I get 500 internal server error and I cannot figure out what I did. It should be giving a message checking to see if the item is already in the cart and if not send a message saying item is in the cart but I can't get past the 500 internal server error.
Page
#extends('layouts.frontend.frontend')
#section('title')
Distinctly Mine - {{$products->name}}
#endsection
#section('content')
<div class="py-3 mb-4 shadow-sm babyblue border-top">
<div class="container">
<h6 class="mb-0">Collections / {{$products->category->name}} / {{$products->name}}</h6>
</div>
</div>
<div class="container">
<div class="card-shadow shadow-sm product_data">
<div class="card-body">
<div class="row">
<div class="col-md-4 border-right">
<div class="img-hover-zoom img-hover-zoom--xyz card-img-top">
<img src="{{ asset('backend/uploads/products/'.$products->image) }}" class="w-100 h-100" alt="{{$products->name}}">
</div>
</div>
<div class="col-md-8">
<h2 class="mb-0">{{ $products->name}}</h2>
<hr>
<label for="" class="me-3">Price: ${{$products->original_price}}</label>
<p class="mt-3">{!! $products->small_description !!}</p>
<hr>
#if($products->qty > 0)
<label for="" class="badge bg-success text-dark fw-bold">In Stock</label>
#else
<label for="" class="badge bg-danger text dark fw-bold">Out of Stock</label>
#endif
<div class="row mt-2">
<div class="col-md-2">
<input type="hidden" value="{{$products->id}}" class="prod_id">
<label for="Quantity">Quantity</label>
<div class="input-group text-center mb-3" style="width:130px">
<button type="button" class="input-group-text decrement-btn">-</button>
<input type="text" name="quantity" value="1" class="form-control qty-input" />
<button type="button" class="input-group-text increment-btn">+</button>
</div>
</div>
<div class="col-md-10">
<br />
<button type="button" class="btn btn-warning text-dark fw-bold ms-3 float-start"><i class=" me-1 fa fa-heart text-danger me-1"></i>Add To Wishlist</button>
<button type="button" class="btn btn-success ms-3 float-start text-dark fw-bold addToCartBtn"><i class="me-1 fa fa-shopping-cart text-dark me-1"></i>Add to Cart</button>
</div>
<hr>
<h2>Description</h2>
{{$products->description}}
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
<script>
$(document).ready(function (){
$('.addToCartBtn').click(function (e){
e.preventDefault();
var product_id = $(this).closest('.product_data').find('.prod_id').val();
var product_qty = $(this).closest('.product_data').find('.qty-input').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method: "POST",
url: "/add-to-cart",
data: {
'product_id': product_id,
'product_qty': product_qty,
},
dataType: "dataType",
success: function (response){
alert(response.status);
}
});
});
$('.increment-btn').click(function (e){
e.preventDefault();
var inc_value = $('.qty-input').val();
var value = parseInt(inc_value,10);
value = isNaN(value) ? 0 :value;
if(value < 10)
{
value++;
$('.qty-input').val(value);
}
});
$('.decrement-btn').click(function (e){
e.preventDefault();
var dec_value = $('.qty-input').val();
var value = parseInt(dec_value,10);
value = isNaN(value) ? 0 :value;
if(value > 1)
{
value--;
$('.qty-input').val(value);
}
});
});
</script>
#endsection
Route
Route::middleware(['auth'])->group(function (){
Route::post('/add-to-cart',[CartController::class,'addProduct']);
});
Controller
<?php
namespace App\Http\Controllers\Frontend;
use App\Models\Product;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class CartController extends Controller
{
public function addProduct(Request $request)
{
$product_id = $request->input('product_id');
$product_qty = $request->input('product_qty');
if(Auth::check())
{
$prod_check = Product::where('id',$product_id)->first();
if($prod_check)
{
if(Cart::where('prod_id',$product_id)->where('user_id',Auth::id())->exists())
{
return response()->json(['status' => $prod_check->name." Already Added to cart"]);
}else{
$cartItem = new Cart();
$cartItem->prod_id = $product_id;
$cartItem->user_id = Auth::id();
$cartItem->prod_qty = $product_qty;
$cartItem->save();
return response()->json(['status'=>$prod_check->name." Added to cart"]);
}
}
}
else{
return response()->json(['status'=> "Login To Continue"]);
}
}
}

Async Method returns 404

I got the following problem.
in my Controller, this method is supposed to return a JSON with the pets from the database. but is being called, the server returns a 404.
public async Task<JsonResult> GetPetsAsync(int ownerId )
{
var pets = await _dataContext.Pets
.Where(p => p.Owner.Id == ownerId)
.OrderBy(p => p.Name)
.ToListAsync();
return Json(pets);
}
=====================================================
This is the form that provides the OwnerId for the method to find the pets for that particular owner.
<div class="row m-auto align-content-center">
<div class="col-md-4">
<form asp-action="Assign" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Id" />
<div class="form-group">
<label asp-for="OwnerId" class="form-label fw-bold"></label>
<select asp-for="OwnerId" asp-items="Model.Owners" class="form-control"></select>
<span asp-validation-for="OwnerId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PetId" class="form-label fw-bold"></label>
<select asp-for="PetId" asp-items="Model.Pets" class="form-control"></select>
<span asp-validation-for="PetId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Remarks" class="form-label fw-bold "></label>
<textarea asp-for="Remarks" class="form-control"></textarea>
<span asp-validation-for="Remarks" class="text-danger"></span>
</div>
<div class="form-group mt-3">
<button value="Assign" type="submit" class="btn btn-primary btn-sm"><i class="bi bi-calendar-plus-fill"></i></button>
<a asp-action="Index" class="btn btn-success btn-sm"><i class="bi bi-arrow-return-left"></i> Go Back</a>
<span asp-validation-for="Remarks" class="text-danger"></span>
</div>
</form>
</div>
</div>
In my View -- the AJAX request to GetPetsAsync
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(document).ready(function () {
$("#OwnerId").change(function () {
$("#PetId").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetPetsAsync", "Agenda")',
//Take the OwnerId and send it to the JsonResult Method to retrieve the pets
data: { ownerId: $("#OwnerId").val() },
dataType: 'Json',
success: function (pets) {
$("#PetId").append('<option value="0">(Select a pet...)</option>');
$.each(pets, function (i, pet) {
$("#PetId").append('<option value="'
+ pet.id + '">'
+ pet.name + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve pets. ' + ex.statusText);
}
});
return false;
})
});
</script>
It looks like this feature change is affecting you.
Async suffix for controller action names will be trimmed by default #14716
You can just drop the "Async" suffix from your view-side code. Which is why renaming your method "fixed" your problem.
You have control over this behavior in your app startup with SuppressAsyncSuffixInActionName
builder.Services.AddMvc(options =>
{
options.SuppressAsyncSuffixInActionNames = false;
});
Make sure the "httppost" attribute is used. If you continue to get an error, check the data part in the ajax section.
I found the solution. Incredibly just by changing the Method Name to GetPetAsyncronous the problem was solve. I don’t know why the previous method wouldn’t work. But It worked.

How to make a select field (year list) unique per ID or number and remove the selected year from the dropdown list?

I'm new to laravel, I'm trying to achieve a functionality when selecting a year for a specific ID or number that year will be removed from the dropdown list or it will not be listed.
Below I added screenshots and my code so far. I'm actually struggling to figure this out. :(
Please let me know if you need to check my controller.php and others.
Here's my code:
JS:
$(document).ready(function () {
// input fields
$("#tax-dec-form").on('submit', function (e) {
e.preventDefault()
$('#tax-dec-form').find('span.error').remove() //resets error messages
let _url = null;
let data = $('#tax-dec-form').serialize();
if ($('#tax-dec-form').hasClass('new')) {
_url = 'add-tax-info'
data = $('#tax-dec-form').serialize() + "&pin_id=" + pin_id
} else {
_url = 'update-tax-info'
}
$.ajax({
url: _url,
type: "POST",
data: data,
success: function (response) {
if (response.code == 200) {
//console.log(response)
$('#tax-dec-form').removeClass('new');
swal({ title: "Success!", text: response.message, type: "success", buttonsStyling: false, confirmButtonClass: "btn btn-success" })
}
},
error: function (response) {
console.warn(response.responseJSON.errors)
$.each(response.responseJSON.errors, function (field_name, error) {
if ($(document).find('#tax-dec-form [name=' + field_name + ']').next().is('span')) {
$(document).find('#tax-dec-form [name=' + field_name + ']').next('span').remove()
}
$(document).find('#tax-dec-form [name=' + field_name + ']').after('<span class="error text-danger">' + error + '</span>')
})
}
})
})
$('[data-toggle="tooltip"]').tooltip()
})
//for dynamic year list
$(document).ready(function () {
var d = new Date();
for (var i = 0; i <= 40; i++) {
var option = "<option value=" + parseInt(d.getFullYear() + i) + ">" + parseInt(d.getFullYear() + i) + "</option>"
$('[id*=DropDownList1]').append(option);
}
});
Blade.php:
<div class="content menu-css">
<div class="container-fluid">
{{-- upper form here --}}
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header card-header-primary">
<h4 class="card-title">Tax Information</h4>
<p class="card-category">Please complete all fields</p>
</div>
<div class="form-group">&nbsp</div>
<div class="card-body">
#if (session('status'))
<div class="row">
<div class="col-sm-12">
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<i class="material-icons">close</i>
</button>
<span>{{ session('status') }}</span>
</div>
</div>
</div>
#endif
<div class="form_container">
<form action="/action_page.php" id="tax-dec-form" {{$taxesInfo !== null ? '' : 'class=new'}}>
#csrf
<div class="form-group">
<label for="taxdeclarationnumber">Tax Declaration No:</label>
<input value="{{ $taxesInfo->tax_declaration_number ?? ''}}" type="text" class="form-control" name="tax_declaration_number" placeholder="Input Tax Declaration No..">
</div>
<div class="form-group">&nbsp</div>
<div class="form-group">
<label for="current">Current RPT: </label>
<input type="text" value="{{ $taxesInfo->current_rpt ?? ''}}" class="form-control" name="current_rpt" placeholder="Input Current RPT..">
</div>
<div class="form-group">
<label for="years" class="bmd-label-static">Select Tax Declaration Year</label>
<select id="DropDownList1" class="custom-select mr-sm-2" data-style="btn btn-secondary" name="year">
</select>
</div>
</form>
</div>
<div class="clearfix"> </div>
<div id="form-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal" id="btn-save1">Save</button>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
</div>
</div>

Expand Collapse Icons with Vue Js and Bootstrap

I have a Bootstrap accordion with the expand collapse panels,which works fine.
But when expanded it should display minus icon which is not working well for me.
When I click to expand all the panel's icons are changed to minus instead of just changing the one which was expanded.
I have my code in the Vue JS template as below
Am calling the toggle function onclick to toggle the icons, but its doing it for all the other panels too.
How can I fix this? Thanks in advance.
Vue.component('accordion', {
data: function () {
return {
alerts: [],
sound: '',
collapsed:true
}
},
template: `
<div>
<div v-for="(alert, index ) in alerts" class="panel panel-default">
<div class="panel-heading" v-bind:style="'background-color:'+alert.color" role="tab" v-bind:id="'heading'+index" >
<a role="button" data-toggle="collapse" data-parent="#accordion"
v-bind:href="'#collapse'+index" aria-expanded="true" v-on:click="toggle">
<i id="collapseExpand" v-show="collapsed" class="more-less fa fa-plus"></i>
<i id="collapseExpand" v-show="!collapsed" class="more-less fa fa-minus"></i>
<h4 class="panel-title">#{{ alert.description }}</h4></a>
</div>
<div v-bind:id="'collapse'+index" class="panel-collapse collapse" role="tabpanel">
<div class="panel-body">
<div>#{{ alert.comment }}</div>
<div class="row">
<form v-bind:id="'form_'+index" v-bind:name="'form_'+index" v-bind:action="route" method="POST" style="display: inline;">
<input type="hidden" name="_token" :value="csrf">
<input type ="hidden" v-bind:id="'trigger_id_'+alert.triggerid" name = "trigger_id" v-bind:value="alert.triggerid">
<div class="col-lg-12">
<div class="input-group">
<input type="text" v-bind:id="'ack_msg_'+alert.triggerid" name="ack_msg" class="form-control"
placeholder="Acknowledge Message...">
<span class="input-group-btn">
<button class="btn btn-primary" type="submit">Save</button>
</span>
</div>
</div>
</form>
</div>
</div>
<div class="panel-footer">#{{ alert.timestamp }}</div>
</div>
</div>
<input type="hidden" id="audioFile" name="audioFile" v-bind:value="sound">
</div>`,
mounted: function () {
this.loadData();
setInterval(function () {
this.loadData();
}.bind(this), 1000);
},
methods: {
loadData: function () {
$.get('{{ route('getAlertsPersistent') }}', function (response) {
this.alerts = response;
this.sound = this.alerts[0].sound
}.bind(this));
},
toggle(){
this.collapsed = !this.collapsed ;
}
},
});
new Vue({el: '#accordion'});
You want to separate your accordion item that you want to loop. In that way you can have isolated states in each component.
<div>
<accordion-item
v-for="(alert, index) in alerts"
:alert="alert"
:key="index">
</accordion-item>
</div>
inside your <accordion-item/> you should have collapsed inside your data
The other way around is storing the toggled items in array.
export default {
data: () => ({
toggled: []
}),
methods: {
isActive (item) {
return this.toggled.indexOf(item) >= 0
},
toggleItem (item) {
const index = this.toggled.indexOf(item)
if (index >= 0) {
this.toggled.splice(index, 1)
return
}
this.toggled.push(item)
}
}
}
So you can use it now as follows
<a
role="button"
data-toggle="collapse"
data-parent="#accordion"
v-bind:href="'#collapse'+index"
aria-expanded="true"
v-on:click="toggleItem(index)">
<i
:class="[isActive(index) ? 'fa-minus' : 'fa-plus']"
class="more-less fa"></i>
<h4 class="panel-title">#{{ alert.description }}</h4>
</a>
btw you're looping an id=collapseExpand which will cause you problem. instead try :id="'collapseExpand' + index"

Components. Send request with file via vue.http.post()

I have vuejs2 component on page (single file component). It's a simple bootstrap modal window with one file input. I only need to upload one file (no mutlifile upload or etc.)
What is in file:
<template>
<div class="modal fade" id="upload-file-modal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Upload file</h4>
</div>
<form id="app-file-upload-form" name="appFileUploadForm" #submit.prevent="uploadAppFile" novalidate enctype="multipart/form-data">
<div class="modal-body">
<div class="form-group">
<label for="app-file-fileinput">File</label>
<input type="file" name="file" id="app-file-fileinput" class="form-control" v-el="file" #change="attachFile">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Upload</button>
</div>
</form>
</div>
</div>
</div>
<script>
export default {
data() {
return {
file: ''
}
},
methods: {
attachFile(e) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.file = files[0];
},
uploadAppFile() {
console.log(this.file);
Vue.http.post('/api/v1/apps/' + this.appId + '/files', { file: this.file}).then((response) => {
console.log(response);
}, (response) => {
console.log(response);
});
}
}
}
So i have laravel controller for handle it.
public function upload(Request $request)
{
$attachedFile = $request->file;
return response()->json($request->all());
}
I put return response->json() for kinda debug this. When i attach file, file attaching to component(model?) field and not empty. But when vue.http.post happening the file comes to empty object.
First is console.log(file)
Second is server response.
I also tried with FormData()... it didn't work.
ps: i cut version field from code.
After few more times with formdata i got file upload working. Just put variable inside method.
uploadAppFile() {
let data = new FormData();
data.append('file', this.file);
Vue.http.post('/api/v1/apps/' + this.appId + '/files', data).then((response) => {});
}

Resources